Let's say I have three classes A, B and C.
All have a public void foo()
method defined.
Now from C's foo()
method I want to invoke A's foo()
method (NOT its parent B's method but the super super class A's method).
I tried super.super.foo();
, but it's invalid syntax. How can I achieve this?
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.
Definition and Usage 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.
2) super can be used to invoke parent class method The super keyword can also be used to invoke parent class method. It should be used if subclass contains the same method as parent class. In other words, it is used if method is overridden.
The superclass method is used to access the parent class inside a child class. This method has a variety of uses when inheriting parent members.
You can't even use reflection. Something like
Class superSuperClass = this.getClass().getSuperclass().getSuperclass(); superSuperClass.getMethod("foo").invoke(this);
would lead to an InvocationTargetException
, because even if you call the foo-Method on the superSuperClass, it will still use C.foo()
when you specify "this" in invoke. This is a consequence from the fact that all Java methods are virtual methods.
It seems you need help from the B class (e.g. by defining a superFoo(){ super.foo(); }
method).
That said, it looks like a design problem if you try something like this, so it would be helpful to give us some background: Why you need to do 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