如何通过代码创建新对象

时间:2016-10-17 19:15:48

标签: java

对于一个类项目,我们必须用Java创建一个家庭。所以我们的人类看起来像这样:

public class Person
{
    String firstName;
    String middleName;
    boolean isMale;
    int age;

    //Make new person with age set to 0
    public Person(String firstName, String middleName, boolean isMale)
    {
        this.firstName = firstName.trim().toUpperCase();
        this.middleName = middleName.trim().toUpperCase();
        this.isMale = isMale;
        this.age = 0;
    }
}

我们正在尝试对此进行另一个类调用,并根据输入创建一个新的Person

public class Family
{
    String surname;
    Person husband;
    Person wife;
    Person child

    //////
    //The following is supposed to make a new Person() with the following variables set. However, I don't know how to do this.
    //////

    public void haveChild(String firstName, String middleName, boolean isMale)
    {
        Person baby;
        System.out.println(firstName.trim().toUpperCase() + " is born."); //Prints Child's name
        this.child = child; //Set's the created Person() object as variable Child, or at least that's what this is intended to do.
    }
}

这就是我到目前为止所拥有的。我似乎无法弄清楚接下来需要做什么。我试图使用new Person();和其他变体,但它似乎不起作用。

2 个答案:

答案 0 :(得分:2)

public void haveChild(String firstName, String middleName, boolean isMale)
{
    System.out.println(firstName.trim().toUpperCase() + " is born."); //Prints Child's name
    this.child = new Person(firstName, middleName, isMale); //Set's the created Person() object as variable Child, or at least that's what this is intended to do.
}

答案 1 :(得分:1)

我不确切知道你在寻找什么,但希望这可以在某种程度上有所帮助:

clean

然后你可以创建一个方法来获取你家庭班中每个人类的详细信息#Getters and Setters!