方法调用总是根据对象的运行时类型确定,但是如何从继承实例调用基类的隐藏方法?
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'
}
}
例如上面,如何从实例调用类的str()
方法,最好不使用反射?Base
Impl
使用关键字 super
访问超类成员
如果您的方法覆盖了其超类的方法之一,则可以通过使用关键字来调用被覆盖的方法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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句