package com.javarush.task.task07.task0724;
/*
Семейная перепись
*/
public class Solution {
public static void main(String[] args) {
Human grandfather1 = new Human("Павел", true, 75);
Human grandmother1 = new Human("Катя", false, 77);
Human grandfather2 = new Human("Михаил", true, 82);
Human grandmother2 = new Human("Вера", false, 82);
Human father = new Human("Григорий", true, 64, grandfather1, grandmother1);
Human mother = new Human("Татьяна", false, 62, grandfather2, grandmother2);
Human son1 = new Human("Александр", true, 36, father, mother);
Human son2 = new Human("Михаил", true, 35, father, mother);
Human son3 = new Human("Павел", true, 35, father, mother);
System.out.println(grandfather1.toString());
System.out.println(grandmother1.toString());
System.out.println(grandfather2.toString());
System.out.println(grandmother2.toString());
System.out.println(father.toString());
System.out.println(mother.toString());
System.out.println(son1.toString());
System.out.println(son2.toString());
System.out.println(son3.toString());
// напишите тут ваш код
}
public static class Human {
String name;
boolean sex;
int age;
Human father;
Human mother;
public Human(String name, boolean sex, int age) {
name = this.name;
sex = this.sex;
age = this.age;
}
public Human(String name, boolean sex, int age, Human father, Human mother) {
name = this.name;
sex = this.sex;
age = this.age;
father = this.father;
mother = this.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;
}
}
}
Выводит на экран:
Имя: null, пол: женский, возраст: 0
Имя: null, пол: женский, возраст: 0
Имя: null, пол: женский, возраст: 0
Имя: null, пол: женский, возраст: 0
Имя: null, пол: женский, возраст: 0
Имя: null, пол: женский, возраст: 0
Имя: null, пол: женский, возраст: 0
Имя: null, пол: женский, возраст: 0
Имя: null, пол: женский, возраст: 0
Павел
22 уровень
Программа прошла все проверки, но вывод то неправильный. Код не копируйте, работает неправильно. В чем ошибка не пойму.
Решен
Комментарии (1)
- популярные
- новые
- старые
Для того, чтобы оставить комментарий Вы должны авторизоваться
Павел Безумный учёный Expert
5 июля 2020, 17:59решение
Инициализация полей класса Human в конструкторе должна производиться так:
name - это локальная переменная конструктора, посредством которой передаётся ссылка на строку при создании объекта. А переменная this.name - это поле класса Human, которому и присваивается ссылка из локальной переменной name. Оператор присваивания = работает так: значение или ссылка справа от оператора записывается в переменную, находящуюся слева от оператора.
+3