【发布时间】:2011-03-07 04:37:02
【问题描述】:
如果我有一个子类具有我从父类重写的方法,并且在非常特定的情况下我想使用原始方法,我该如何调用这些方法?
【问题讨论】:
标签: java inheritance
如果我有一个子类具有我从父类重写的方法,并且在非常特定的情况下我想使用原始方法,我该如何调用这些方法?
【问题讨论】:
标签: java inheritance
调用超级
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;
}
}
【讨论】:
这就是super 的用途。如果你重写方法method,那么你可以这样实现它:
protected void method() {
if (special_conditions()) {
super.method();
} else {
// do your thing
}
}
【讨论】:
一般可以使用关键字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();
}
}
取自http://download.oracle.com/javase/tutorial/java/IandI/super.html
【讨论】: