[英]Inherited Object printing as null in Java
我们被要求在父类Person中将字符串“名称”定义为私有。 但是,当我尝试显示Person和Employee对象的名称时,Employee名称显示为“ null”。 我不允许将“名称”定义为公共名称。
人类:
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;
}
员工类别:
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空,身高为65,体重为128; 您的BMI为:21.297988165680472 null,身高为60,体重为120; 您的BMI是:23.433333333333334
我通过电子邮件询问教授,她说因为在父类Person中定义了toString(),所以不会发生此错误。 我的语法错误吗? 逻辑错了吗?
问题是您的Employee
构造函数正在调用默认的Person
构造函数(该调用是由编译器自动注入的,因为已定义了默认构造函数。您可以在Person
删除该默认构造函数,并且会看到它没有编译。 )。
您应该调用在Employee构造函数中接收名称的构造函数,而不是设置属性(该属性不应编译,btw)
public Employee(String name, int id) {
super(name);
this.id = id;
}
您应该删除行this.name = name;
在Employee构造函数中,并添加对super(name);
的调用super(name);
作为同一构造函数的第一行。
这是因为它在Person类中是私有的,因此您无法在Employee类中对其进行访问,因此无法直接从那里进行设置。
改变这个
public Employee(String name, int id) {
this.id = id;
this.name = name;
}
为此,它将调用您需要设置名称的构造方法:
public Employee(String name, int id) {
super(name);
this.id = id;
}
我不确定您的此类如何编译
public class Employee extends Person {
private int id;
public Employee(String name, int id) {
this.id = id;
this.name = name;
}
}
当您说this.name = name且Person.name是私有的时,如果您尚未在Employee类中定义另一个名为name的变量,则不应编译该代码。
回到您的问题,您需要在Employee构造器中调用Person的构造函数,如下所示
public class Employee extends Person {
private int id;
public Employee(String name, int id) {
super(name);
this.id = id;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.