java - 如何访问从父类(super class)传递下来的子类属性?

标签 java inheritance

我有一个从其父类扩展的子类,但我无法理解如何从从父类继承的子类访问对象属性。

在我的示例中,我将调用从 Acquaintance 继承 namephone 的类 Friend,但是有自己的变量birthdateaddress。创建后,我想打印 Friend 对象的内容,其中包括 namephonebirthdate地址

因为我希望我的变量都是私有(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/

相关文章:

JavaFX - TableView 的问题(NullPointerException)

java - 计数以 x 开头的字符串,并存储在 Array Android Studio 中

java - 在扩展 AsyncTask 的类中使用 DoInBackground 方法来更改不是 MainActivity 的 Activity 中 TextView 的文本

javascript - 如何确保扩展类必须在 TypeScript 中设置属性值?

javascript - 子类不能调用其父类的原型(prototype)方法

java - 在 arraylist 中使用多态性时调用子方法

java - 为什么我的父类(super class)对象实例会影响我继承的类对象实例?

java - 从 netbeans/java 连接到 Linux 服务器上的 mySQL 服务器时遇到问题

java - 如何继承两个类

java - GC_CONCURRENT不停运行