Reputation: 37
I have class A
, and class B
inherit class A
, and class C
inherit class B
,
and all of the classes have this method:
public void someMethod();
How can i call this method from class C
so the method from class A
would be implemented?
Upvotes: 3
Views: 1120
Reputation: 1865
As a matter of design, you can declare someMethod()
final
in class A, then all three have it, but cannot change the implementation. Then have a second method which does the second thing needed in B.
Or for a more complex situation, some refactoring idea like this may also help: http://www.refactoring.com/catalog/formTemplateMethod.html
Upvotes: 0
Reputation: 425013
You can't.
You can call the implementation from the parent:
super.someMethod();
But that's all. If B defines an implementation, that's the one that will get called. If not, A will get called, but you can't force A to be called (bypassing B).
The reason is that because C inherits from B, it's up to the implementation in B whether or not the implementation in A is used. There may be a very good reason why the implementation in A should not be used.
If you want C to use A's implementation, inherit directly from A. If you need some code from B, consider delegating to an instance of B.
Upvotes: 4
Reputation: 6154
Any class can only access instance of its immediate parent using super
. You can not access grandparent.
Which means in C
's member function you can invoke super.someMethod()
. This will invoke, B
's someMethod()
implementation. However, any given object does not have access to instance of its grandparent.
Hence you can not invoke A.someMethod()
implementation from C
.
Upvotes: 2