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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With