我有一个从其父类扩展的子类,但我无法理解如何从从父类继承的子类访问对象属性。
在我的示例中,我将调用从 Acquaintance
继承 name
和 phone
的类 Friend
,但是有自己的变量birthdate
和address
。创建后,我想打印 Friend
对象的内容,其中包括 name
、phone
、birthdate
、 地址
。
因为我希望我的变量都是私有(private)的,所以我想我会使用 getter,但我不确定在这种情况下如何调用父类。
public class Acquaintance {
private String name;
private String phone;
public Acquaintance(String name, String phone) {
this.name = name;
this.phone = phone;
}
public static String getName() {
return this.name;
}
public String getPhone() {
return this.phone;
}
public void printContact() {
System.out.println("Name: " + this.name + ", Phone: " + this.phone);
}
}
子类:
public class Friend extends Acquaintance {
private String address;
private String birthdate;
public Friend(String name, String phone, String birthdate, String address) {
super(name, phone);
this.address = address;
this.birthdate = birthdate;
}
public void printContact() {
/* This is where I'm having trouble.
I don't know how to access the name,
and phone which are contained in the superclass.
*/
System.out.println("Name: " + "Phone: " + "Birthdate: " + this.birthdate + "Address: " + this.address);
}
}
最佳答案
父类 Acquaintance
中的 Getter(例如 getName
)是公共(public)的,因此在这种情况下,它们对子类 Friend
是可见的。因此,只需使用像 getName
这样的 getter 就可以从子类中访问父类(super class)中定义的字段。
在您的情况下,首先只需删除 static
修饰符即可使 getName
方法成为实例方法。然后像这样更改代码,
public void printContact() {
/*
* This is where I'm having trouble. I don't know how to access the name, and
* phone which are contained in the superclass.
*/
getName();
}
关于java - 如何访问从父类(super class)传递下来的子类属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52446645/