I have a class that extends a class that I need to overide, but I need to call that class's parent class. since I can't call super since that will execute the direct parent what is the best way to get the parent of my parent class?
I am sure this is a basic question, but its been a while since I have been doing any java.
class A
{
public void myMethod()
{ /* ... */ }
}
class B extends A
{
public void myMethod()
{ /* Another code */ }
}
class C extends B
{
I need to call Class A here
{ /* Another code */ }
}
You don't: it violates encapsulation.
It's fine to say, "No, I don't want my own behaviour - I want my parent's behaviour" because it's assumed that you'll only do so when it maintains your own state correctly.
However, you can't bypass your parent's behaviour - that would stop it from enforcing its own consistency. If the parent class wants to allow you to call the grandparent method directly, it can expose that via a separate method... but that's up to the parent class.
What I do for this case is:
Make the object of class A inside the Class C and access the Class A there. This Example which clarifies more details:
}
The output of this example is:
What you are asking is bad practice, What you are saying is that C is not a B, but an A. What you need to do is have C inherit from A. Then you can call super.
If not this is the only way...
You can't because it has been overridden by B. There is no instance of A inside C.
The thing is that you want to call a method of the class A, but from which instance? You have instantiated C, which is a class with a couple of own and inherited methods from B. If B is overriding a method of A, you can't access it from C, because the method itself belongs to C (is not a method of B, it has been inherited and now it's in C)
Possible workarounds:
B does not override
myMethod()
C receives an instance of A and saves it as a class property.
myMethod()
in A is static and you useA.myMethod()
(I don't recommend it)You can't call A's method directly. In the few cases that I've hit this, the solution was to add a method in A to expose it's implementation. E.g.
The scheme separates the public interface (doMyMethod) from the implementation (doAMyMethod). Inheritance does depend upon implementation details, and so this isn't strictly so bad, but I would try to avoid it if possible as it creates a tight coupling between the implementation in A and C.
Besides what pakore answered, you could also chain
super.myMethod()
calls if that works for you. You will callmyMethod()
from A from themyMethod()
in B.You will eventually be calling myMethod from A, but indirectly... If that works for you.