In the example below, how can I access, from C
, the method method()
of the class A
?
class A {
public void method() { }
}
class B extends A{
public void method() { }
}
class C extends B{
public void method() { }
void test() {
method(); // C.method()
super.method(); // B.method()
C.super.method(); // B.method()
B.super.method(); // ERROR <- What I want to know
}
}
The error I am getting is
No enclosing instance of the type B is accessible in scope
Answer: No, this is not possible. Java doesn't allow it. Similar question.
You can't - and very deliberately. It would violate encapsulation. You'd be skipping whatever B.method
wants to do - possibly validating arguments (assuming there were any), enforcing invariants etc.
How could you expect B
to keep a consistent view of its world if any derived class can just skip whatever behaviour it's defined?
If the behaviour B provides isn't appropriate for C, it shouldn't extend it. Don't try to abuse inheritance like this.