[英]Access shadowed methods based on the casting type of the object
Method calls are always determined based on the runtime type of the object, however how can I call shadowed methods of base classes from an inherit instance? 方法调用总是根据对象的运行时类型确定的,但是如何从继承实例中调用基类的影子方法呢?
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'
}
}
For example above, how can I call the str()
method of Base
class from an Impl
instance, preferably without using reflection? 例如,上面的示例如何从
Impl
实例调用Base
类的str()
方法,最好不使用反射?
Using the Keyword super 使用关键字超级
Accessing Superclass Members 访问超一流成员
If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super
. 如果您的方法覆盖了其超类的方法之一,则可以通过使用关键字
super
来调用覆盖的方法。 You can also use super to refer to a hidden field (although hiding fields is discouraged). 您也可以使用super引用隐藏字段(尽管不建议使用隐藏字段)。 an example below.
下面的例子。
public class Superclass {
public void printMethod() {
System.out.println("Printed in Superclass.");
}
}
calling printMethod since child class 从子类开始调用printMethod
Here is a subclass, called Subclass, that overrides 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();
}
}
if you want to read more https://docs.oracle.com/javase/tutorial/java/IandI/super.html 如果您想阅读更多https://docs.oracle.com/javase/tutorial/java/IandI/super.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.