Java - 对象中具有相同数据类型的多个字段

Java - Multiple fields of same data type in an object

我在一节课后练习继承和组合,决定写一个小程序来尝试一些东西,偶然发现一个问题,我会展示我的代码,它有 4 类 包括 Main.java:

public class Main {

public static void main(String[] args) {

    Person person1 = new Person("Person1", 170); //"Name", height
    Person person2 = new Person("Person2", 200); //"Name", height

    Bed bed1 = new Bed(160);

    Bedroom bedroom1 = new Bedroom(bed1, person1);

    bedroom1.sleep();

public class Bedroom {

private Bed theBed;
private Person thePerson;

//Constructors

public void sleep() {
    if(thePerson.getHeight() > 180) {
        System.out.println("You are too tall to sleep on this bed.");
    } else {
        theBed.sleepOnBed();
    }
}

//Getters

public class Bed {

private Person thePerson;
private int height;

//Constructor

public void sleepOnBed() {
        System.out.println("You sleep on the bed.");
}

//Getters 

public class Person {

private String name;
private int height;

//Constructor

//Getters

我想做的是在 Main.java 中的 bedroom1 对象中同时使用 person1person2,然后测试 sleep() 方法两者都有,但我就是想不出使用它的方法。

我试过类似的东西:

public class Bedroom {

private Bed theBed;
private Person thePerson1;
private Person thePerson2;

public Bedroom(Bed theBed, Person thePerson1, Person thePerson2) {
    this.theBed = theBed;
    this.thePerson1 = thePerson1;
    this.thePerson2 = thePerson2;
} 


public class Main {

public static void main(String[] args) {

    Person person1 = new Person("Person1", 170);
    Person person2 = new Person("Person2", 200);

    Bed bed1 = new Bed(160);

    Bedroom bedroom1 = new Bedroom(bed1, person1, person2);

    bedroom1.sleep(); 

但正如您可能理解的那样,这没有任何结果。我只是太累了,在网上找不到任何线索,可能是因为我使用了错误的关键字idk。

我想让我的程序获取多个数据类型 Person 的对象,看看它们的高度是否符合睡在床上的条件,差不多就是这样。

您可以用卧室中的 Person 对象列表替换 Person class,然后在 sleep 方法中遍历数组。

public Bedroom(Bed bed1, List<Person> aListOfPersons)
{
  this.persons = aListOfPersons;
}

public void sleep()
{
  for(Person aPerson : persons)
   {
      //check for each aPerson if he fits in the bed
   }
 }

欢迎使用 Whosebug,祝您编码愉快!