方法调用始终根据对象的运行时类型确定,但是如何从继承实例调用基类的影子方法?
class Base {
String str = "base";
String str() { return str; }
}
class Impl extends Base {
String str = "impl";
String str() { return str; }
}
class Test {
public static void main(String[] args) {
System.out.println(((Base) new Impl()).str); // print 'base'
System.out.println(((Base) new Impl()).str()); // print 'impl'
}
}
例如上面的例子,如何从 Impl
实例调用 Base
类的 str()
方法,最好不使用反射?
最佳答案
使用关键字 super
访问父类(super class)成员
如果您的方法重写了其父类(super class)的方法之一,则可以通过使用关键字 super
来调用被重写的方法。您还可以使用 super 来引用隐藏字段(尽管不鼓励隐藏字段)。下面是一个例子。
public class Superclass {
public void printMethod() {
System.out.println("Printed in Superclass.");
}
}
从子类开始调用 printMethod
这是一个子类,称为 Subclass,它重写了 printMethod():
public class Subclass extends Superclass {
// overrides printMethod in Superclass
public void printMethod() {
super.printMethod();
System.out.println("Printed in Subclass");
}
public static void main(String[] args) {
Subclass s = new Subclass();
s.printMethod();
}
}
如果你想了解更多 https://docs.oracle.com/javase/tutorial/java/IandI/super.html
关于java - 根据对象的转换类型访问隐藏方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48023564/