我有一个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/