Условия задачи Семейная перепись
Создай класс Human с полями имя(String), пол(boolean), возраст(int), отец(Human), мать(Human). Создай объекты и заполни их так, чтобы получилось: Два дедушки, две бабушки, отец, мать, трое детей. Вывести объекты на экран.
Требования:
1. Программа не должна считывать данные с клавиатуры.
2. Добавить в класс Human поля: имя(String), пол(boolean), возраст(int), отец(Human), мать(Human).
3. Добавить в класс конструктор public Human(String name, boolean sex, int age).
4. Добавить в класс конструктор public Human(String name, boolean sex, int age, Human father, Human mother).
5. Создай 9 разных объектов типа Human (4 объекта без отца и матери и 5 объектов с ними)).
6. Выведи созданные объекты на экран.
public class Solution {
public static void main(String[] args) {
Human ded1=new Human("Ваня",true,96);
Human ded2=new Human("Петя",true,96);
Human babka1=new Human("Маша",false,96);
Human babka2=new Human("Дуся",false,96);
Human father=new Human("Серёжа",true,36,ded1,babka1);
Human mather=new Human("Дусяша",false,26, ded2,babka2);
Human chald1=new Human("Наташа",false,5,father,mather);
Human chald2=new Human("Юля",false,5,father,mather);
Human chald3=new Human("Света",false,5,father,mather);
System.out.println(ded1.toString());
System.out.println(ded2.toString());
System.out.println(babka1.toString());
System.out.println(babka2.toString());
System.out.println(father.toString());
System.out.println(mather.toString());
System.out.println(chald1.toString());
System.out.println(chald2.toString());
System.out.println(chald3.toString());
}
public static class Human {
private String name;
private boolean sex;
private int age;
private Human father;
private Human mother;
public Human(String name, boolean sex, int age)
{
this.name=name;
this.sex=sex;
this.age=age;
}
public Human(String name, boolean sex, int age, Human father,Human mother)
{
this.name=name;
this.sex=sex;
this.age=age;
//this.father=father;
//this.mother=mother;
this.father.name=father.getName();
this.mother.name=mother.getName();
}
public String getName()
{
return this.name;
}
public void setName(String name)
{
this.name=name;
}
public String toString() {
String text = "";
text += "Имя: " + this.name;
text += ", пол: " + (this.sex ? "мужской" : "женский");
text += ", возраст: " + this.age;
if (this.father != null)
text += ", отец: " + this.father.name;
if (this.mother != null)
text += ", мать: " + this.mother.name;
return text;
}
}
}
Дело, если правильно понял, во 2-м конструкторе в полях father and . Изначально я их инициализировал по простому: //this.father=father;
//this.mother=mother;. Всё работало выводило как по заданию, но проверку не проходило. Далее прочитал, что нужно их задавать через методы доступа get and set. Написал методы get and set для получения/установления поля у нужного объекта NAME (так как только оно требуется при выводи информации). В конструкторе попытался обратиться к полям NAME полей father и mother объекта который создает конструктор (коряво написано наверное, но по другому пока не получается) и установить их значения с помощью описанного метода get: this.father.name=father.getName();
this.mother.name=mother.getName(); - ошибка компиляции.
Объясните пожалуйста, что неверно?