如何从子类调用重写的父类方法?
如果我有一个子类,它有从父类重写的方法,并且在非常特殊的情况下我想使用原始方法,我该如何调用这些方法?
打电话给超级
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
来访问父类的function。 例如:
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