Reputation: 23
This seems to be basic question. But worth to clarify before interviews.
I have a non abstract method in abstract class. Its concrete class overridden that method. But I want to call the parent class's original method to invoke rather than overridden method. Is there any way to do it ?
As I can understand there's no way to invoke original method ?
public abstract class Testabstract {
public void t1() {
System.out.println("parent");
}
}
public class Testconcrete extends Testabstract {
public void t2() {
System.out.println("child11");
}
public void t1() {
System.out.println("childss");
}
}
public class Main {
public static void main(String[] args) {
Testconcrete a = new Testconcrete();
a.super.t1();// compile error
a.t2();
}
}
Upvotes: 2
Views: 141
Reputation: 121998
super keyword can use only with in the child class.
For ex you can try doing
public void t2() {
super.t1();
System.out.println("child11");
}
Casting to Parent
also won't work still your underlying element is Child
.
So you cannot access from outside of Child class in a clean way. Don't exactly know if they is any naive way to do that.
Upvotes: 1
Reputation: 37645
Your understanding is correct. Without changing one of classes Testabstract
or Testconcrete
there is no way to invoke the original method on an instance of Testconcrete
.
I don't think it's even possible to do it with reflection.
Upvotes: 0
Reputation: 77167
No, you can't directly invoke the superclass's overridden method. This is by design; the subclass might add some sort of behavior that is necessary for correctness (such as maintaining some sort of cache or other data structure) or functional requirements (such as logging). Bypassing the subclass's functionality would put the correctness of the model at risk and breaks the encapsulation that assures it.
Upvotes: 2