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

后端 未结 3 959
渐次进展
渐次进展 2020-12-07 02:17

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 meth

相关标签:
3条回答
  • 2020-12-07 02:22

    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;
       }
    }
    
    0 讨论(0)
  • 2020-12-07 02:29

    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 讨论(0)
  • 2020-12-07 02:37

    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
        }
    }
    
    0 讨论(0)
提交回复
热议问题