java - 如何将对象作为参数传递到另一个类的构造函数中?

标签 java oop constructor

我有一个java程序,其中创建了一个person类的列表...dateofBirth是person类中的一个对象参数。现在我面临一个问题;如何初始化列表中的 person 对象或如何将 DateOfBirth 对象传递给 Person 的构造函数?

class DateOfBirth{
    private int year;
    private int month;
    private int day;

    DateOfBirth(){
        this.year = 0;
        this.month = 0;
        this.day = 0;
    }

    DateOfBirth(int y, int m, int d){
        if(y>1900){
            year = y;
        }
        else{
            System.err.println("the year is too small too old" );           
        }
        if(0<month && month<13){
            month = m;
        }
        else{
            System.err.println("month should be within 1 to 12.");
        }
        if(0<day && day<30){            
            day = d;
        }           

    }


    public int getYear() {
        return year;
    }

    public int getMonth(){
         return month;
     }
    public int getDay(){
        return day;
    }

}
class Person{
    private String name;
    private int age;
    private DateOfBirth Dob;

    public Person(String name, int age, DateOfBirth dob){
    this.name = name;
    this.age = age;
    this.Dob = dob;
    }

    public String getName() {
        return name;
    }

    public DateOfBirth getDob() {
        return Dob;
    }    

    public int getAge() {
        return age;
    }

}

public class MyList {
    ArrayList<Person> Personlist = new ArrayList<Person>();

    Person person=new Person("John",23,...) // how to pass the DateOfBirth object here?     

}

最佳答案

先创建一个日期,然后将其作为参数传递

 public class MyList {
        ArrayList<Person> Personlist = new ArrayList<Person>();

DateOfBirth date = new DateOfBirth(2000, 1, 1);
    Person person = new Person("John", 16, date);

}

希望这有帮助。

关于java - 如何将对象作为参数传递到另一个类的构造函数中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39720667/

相关文章:

java - List<String> addAll() 方法未添加

JavaFX 与 Java Swing

java - 创建递归方法的返回类型

java - 如何在 OOP 中实现图形层次结构

c# - 如何使这个通用

java - 获取祖先类的泛型类

java - 应用程序重启时的文件读取偏移量

javascript - 静态私有(private)字段 Javascript

c++ - 如何使用 vector 和整数作为类的构造函数

c++ - 当我们进行复制初始化时,复制构造函数或构造函数是否起作用