我們被指示將字符串「名稱」定義爲父類Person中的私有。但是,當我嘗試顯示Person和Employee對象的名稱時,Employee名稱被打印爲「null」。我不允許將「名稱」定義爲公共。繼承對象在Java中打印爲null
Person類:
public class Person {
private String name;
public int weight, height;
public Person() {}
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String toString() {
return this.getName() + ", your height is " + height + " and your weight is "
+ weight;
}
Employee類:
public class Employee extends Person {
private int id;
public Employee(String name, int id) {
this.id = id;
this.name = name;
}
public int getID() {
return id;
}
}
主類:
Person a1 = new Person("Thomas");
a1.height = 70;
a1.weight = 160;
Person a2 = new Employee("Rebecca", 6543);
a2.height = 65;
a2.weight = 128;
Person a3 = new Employee("Janice", 8765);
a3.height = 60;
a3.weight = 120;
Person[] arr = new Person[] {a1, a2, a3};
Person a;
for (int i = 0; i < arr.length; i++) {
a = arr[i];
System.out.println(a.toString() + "; your BMI is: " + a.calcBMI());
}
Person.countEmployees(arr);
輸出:
托馬斯,你的身高是70,體重是160;你的BMI是:22.955102040816328 null,你的身高是65,你的體重是128;你的BMI是:21.297988165680472 null,你的身高是60,體重是120;你的BMI是:23.433333333333334
我通過電子郵件問我的教授,她說因爲toString()是在父類Person中定義的,所以不應該發生這個錯誤。我的語法錯了嗎?邏輯錯誤?
您可以用'protected'? –
這是如何編譯的?「Employee」類中的'this.name = name;'不是你的編譯器錯誤嗎? –
@EmersonFarrugia是的,它包含「this.name = name」時會出錯。我拿出來測試東西,然後打印空對象 – supersaidso