Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 329
John Assymptoth Avatar asked Jan 15 '11 08:01

John Assymptoth


People also ask

How do you call a method of super of super class in Java?

Call to super() must be the first statement in the Derived(Student) Class constructor. If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass.

What is super class in Java with example?

In Java, the superclass, also known as the parent class , is the class from which a child class (or a subclass) inherits its constructors, methods, and attributes. For instance, in our above example, BankAccount was the superclass from which our subclass SavingsAccount inherited its values.

Can we do super super in Java?

The super keyword in Java is a reference variable that is used to refer parent class objects. The super() in Java is a reference variable that is used to refer parent class constructors. super can be used to call parent class' variables and methods. super() can be used to call parent class' constructors only.

What does the super () function do in Java?

The super keyword refers to superclass (parent) objects. It is used to call superclass methods, and to access the superclass constructor. The most common use of the super keyword is to eliminate the confusion between superclasses and subclasses that have methods with the same name.


1 Answers

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.

like image 154
Jon Skeet Avatar answered Sep 20 '22 08:09

Jon Skeet