Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 395
Paul Avatar asked Mar 07 '11 04:03

Paul


2 Answers

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;
   }
}
like image 66
corsiKa Avatar answered Nov 14 '22 23:11

corsiKa


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
    }
}
like image 29
Ted Hopp Avatar answered Nov 14 '22 23:11

Ted Hopp