簡體   English   中英

如何在另一個類的構造函數中將對象作為參數傳遞?

[英]How to pass an object as an argument in a constructor of another class?

我有一個在其中創建人員類別列表的java程序... dateofBirth是人員類別中的對象參數。 現在我面臨一個問題; 如何初始化列表中人員的對象或如何將DateOfBirth對象傳遞給人員的構造函數?

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);

}

希望這可以幫助。

在需要的地方創建DateOfBirth的對象,然后將其像這樣傳遞給構造函數

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

DateOfBirth dob= new DateOfBirth(1992, 2, 3);
    Person person=new Person("John",23,dob);

}

除了@TeunVanDerWijst的答案之外,您還可以在Person類中創建另一個構造函數,該構造函數將在Person類本身中創建實例。 構造函數如下所示。

public Person(String name, int age, int y, int m, int d) {
    this(name, age, new DateOfBirth(y, m, d));
}

this將只調用另一個構造函數,該構造函數將分配新生成的DateOfBirth實例。

現在,您只需將年,月和日傳遞為int即可創建Person的實例。

 Person person=new Person("John", 23, 2000, 9, 12);

如果該dateofbirth屬於某個人,則無需創建新的DateOfBirth對象

做到簡單:

Person person = new Person("John",23,new DateOfBirth(1985,5,5));

甚至像:

try
{
    Personlist.Add(new Person("John",23,new DateOfBirth(1985,5,5)));
}
catch(Exception ex)
{
   //
}

對於建議,切勿使用MyList之類的類名。 列表是集合,MyList是??? 新的收藏類型? 它有什么?? 即使不知道程序在做什么的人也可以理解其目的,並嘗試命名。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM