java 如何从子类调用重写的父类方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5215873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I call an overridden parent class method from a child class?
提问by Paul
If I have a subclass that has methods I've overridden from the parent class, and under very specific situations I want to use the original methods, how do I call those methods?
如果我的子类具有从父类重写的方法,并且在非常特殊的情况下我想使用原始方法,我该如何调用这些方法?
采纳答案by corsiKa
call super
呼叫超级
class A {
int foo () { return 2; }
}
class B extends A {
boolean someCondition;
public B(boolean b) { someCondition = b; }
int foo () {
if(someCondition) return super.foo();
return 3;
}
}
回答by Ted Hopp
That's what super
is for. If you override method method
, then you might implement it like this:
这super
就是为了。如果您覆盖 method method
,那么您可能会像这样实现它:
protected void method() {
if (special_conditions()) {
super.method();
} else {
// do your thing
}
}
回答by booooh
You can generally use the keyword super
to access the parent class's function.
for example:
通常可以使用关键字super
来访问父类的函数。例如:
public class Subclass extends Superclass {
public void printMethod() { //overrides printMethod in Superclass
super.printMethod();
System.out.println("Printed in Subclass");
}
public static void main(String[] args) {
Subclass s = new Subclass();
s.printMethod();
}
}
Taken from http://download.oracle.com/javase/tutorial/java/IandI/super.html
取自http://download.oracle.com/javase/tutorial/java/IandI/super.html