Anthony Dragone Anthony Dragone - 1 month ago 9
Java Question

How to create a new object through code

for a class project, we have to make a family in Java. So our person class looks like this:

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


We're trying to have another class call upon this and make a new
Person
based of inputs.

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.
}
}


So that's what I have so far. I just can't seem to figure out what I need to do next. I've attempted to use
new Person();
and other variations, but it doesn't seem to work.

Answer
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.
}
Comments