Создай класс Human с полями имя(String), пол(boolean), возраст(int), отец(Human), мать(Human). Создай объекты и заполни их так, чтобы получилось: Два дедушки, две бабушки, отец, мать, трое детей. Вывести объекты на экран.
Примечание:
Если написать свой метод String toString() в классе Human, то именно он будет использоваться при выводе объекта на экран.
Пример вывода:
Имя: Аня, пол: женский, возраст: 21, отец: Павел, мать: Катя
Имя: Катя, пол: женский, возраст: 55
Имя: Игорь, пол: мужской, возраст: 2, отец: Михаил, мать: Аня
…
Требования:
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("Vasya", true, 70, null, null);
Human babka1 = new Human("Valya", false, 50, null, null);
Human ded2 = new Human("Misha", true, 60, null, null);
Human babka2 = new Human("Masha", false, 40, null, null);
Human father = new Human("Sasha", true, 30, ded1, babka1);
Human mother = new Human("Katya", false, 20, ded2, babka2);
Human child = new Human("Natasha", false, 10, father, mother);
Human child2 = new Human("Tanya", false, 8, father, mother);
Human child3 = new Human("Roma", true, 6, father, mother);
System.out.println(ded1);
System.out.println(babka1);
System.out.println(ded2);
System.out.println(babka2);
System.out.println(father);
System.out.println(mother);
System.out.println(child);
System.out.println(child2);
System.out.println(child3);
}
public static class Human {
String name;
boolean sex;
int age;
Human mother;
Human father;
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;
}
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;
}
}
}