Как указать родителя в конструкторе?
public class Solution {
public static void main(String[] args) {
Human.list.add(new Human("Макар", true, 60));
Human.list.add(new Human("Люба", false, 55));
Human.list.add(new Human("Петр", true, 40,null,null));//как здесь вместо null указать, что родитель этого объекта - это объект с именем "Макар" ?
Human.list.add(new Human("Макcим", true, 60));
Human.list.forEach(System.out::println);
}
public static class Human {
public static List<Human> list = new ArrayList<>();
String name;
boolean sex;
int age;
Human father;
Human mother;
public Human(String name, boolean sex, int age) {
this.name = name;
this.sex = sex;
this.age = age;
list.add(Human.this);
}
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;
list.add(Human.this);
}
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;
}
}
}
Ответы (1 шт):
Автор решения: gil9red
→ Ссылка
public static void main(String[] args) {
Human father = new Human("Макар", true, 60);
Human mother = new Human("Люба", false, 55);
Human.list.add(father);
Human.list.add(mother);
Human.list.add(new Human("Петр", true, 40,father,mother));
Human.list.add(new Human("Макcим", true, 60));
Human.list.forEach(System.out::println);
}