开发者

How do I call an overridden parent class method from a child class?

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?


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;
   }
}


That's what super is for. If you override method method, then you might implement it like this:

protected void method() {
    if (special_conditions()) {
        super.method();
    } else {
        // do your thing
    }
}


You can generally use the keyword super to access the parent class's function. for example:

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜