我可以从超类方法访问子类字段吗?

时间:2019-03-19 00:37:35

标签: java inheritance subclass superclass

我有一个抽象超类:

public abstract class Parent{
    protected String name = "Parent"; 

    public void printName(){
        System.out.println(name); 
    }
}

我有一个子班:

public class Child extends Parent{
    protected String name = "Child"; 
}

当我这样做时:

Child child = new Child(); 
child.printName(); 

我希望它打印“ Child”,但它打印“ Parent”。有没有办法使继承的方法使用子类的值?理想情况下,我将避免在每个子类中使用重复的printName()方法。

0 个答案:

没有答案