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

0 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?     

}
Run Code Online (Sandbox Code Playgroud)

Teu*_*jst 5

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

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

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

}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.

  • 你犯了一个错误,人是=新人("约翰",23岁,约会); 但是+1 :) (2认同)