【发布时间】:2016-09-27 09:12:33
【问题描述】:
我有这个 java 程序,其中创建了一个人员类列表... dateofBirth 是人员类中的一个对象参数。现在我面临一个问题;如何初始化列表中的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?
}
【问题讨论】:
-
Person person=new Person("John",23,new DateOfBirth(1990,10,10)) -
热情,您应该添加您的评论作为答案
-
顺便说一句,当你有 DOB 时为什么要通过年龄.. 根据 DOB 计算年龄
-
顺便说一句,人也是在 30 日和 31 日出生的 :)
-
@Nevado 然而,你必须承认这段代码不会有闰年的问题。这是大多数“自己做”约会内容的一个非常常见的问题。 :P
标签: java oop constructor