How do I access the super-super class, in Java? [Mini-example inside]

John Assymptoth picture John Assymptoth · Jan 15, 2011 · Viewed 24.7k times · Source

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.

Answer

Jon Skeet picture Jon Skeet · Jan 15, 2011

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.