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

Java—对象中具有相同数据类型的多个字段,java,class,object,inheritance,composition,Java,Class,Object,Inheritance,Composition,一堂课后,我在练习继承和组合,决定编写一个小程序来尝试一些东西,偶然发现一个问题,我将展示我的代码,它有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); //"

一堂课后,我在练习继承和组合,决定编写一个小程序来尝试一些东西,偶然发现一个问题,我将展示我的代码,它有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();
我想做的是在Main.java中的beddroom1对象中同时使用person1和person2,然后在这两个对象上测试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对象列表,然后在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
   }
 }

欢迎使用Stackoverflow和快乐编码

您可以定义一个Person数组,并将其传递给Person构造函数。然后您可以迭代数组并检查所需的条件。当您这样做时,您需要在Bed对象中设置验证条件的人。除非您使用的是原语,否则通常最好使用列表而不是数组。这样,您就不在乎实现是什么了。啊,该死!在我的课程中,我还没有得到数组或列表!谢谢您的回答和热烈欢迎。@Nedotian如果这已经回答了您的问题,请将此问题标记为已回答。@Novatata谢谢您提供的信息,我已经相应地更改了代码。
public class Person {

private String name;
private int height;

//Constructor

//Getters
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(); 
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
   }
 }