Reputation: 26054
I have a class C1
:
public class C1 {
public void method() {
//Do something
}
protected void anotherMethod() {
if (something) {
method();
/*Here, I want to call the method C1.method,
* but C2.method is called
*/
}
}
}
and another class C2
that extends
it and overrides
the method
:
public class C2 extends C1 {
@Override
public void method() {
if (something) {
anotherMethod();
} else {
super.method();
}
}
}
My problem is described in the code comment. I can't run parent method in the parent class. What is the reason?
Upvotes: 3
Views: 86
Reputation: 234715
Annoyingly, you can't (setting aside reflective hacks).
But you could do something on the lines
public class C1 {
public final void _method() /*rename to taste*/{
}
public void method(){
_method();
}
}
and override method
in your derived class. If you specifically require the base class method, then call _method()
. I think that's the nearest to writing C1::method()
which is permissible in C++.
Upvotes: 2
Reputation: 2614
As far as your C2
class is concerned the anotherMethod()
is not overriden so it calls its own method()
if something
is true.
Override it as follows:
@Override
protected void anotherMethod() {
if (something) {
super.method(); //Here, I want to call the method `C1.method`, but `C2.method` is called
}
}
to call the parent method from child's anotherMethod()
definition.
Upvotes: 1