Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling super super class method

Let's say I have three classes A, B and C.

  • B extends A
  • C extends B

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?

like image 593
Harish Avatar asked Aug 11 '10 07:08

Harish


People also ask

Can we call super super method 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 calling the super () method do?

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.

Can we call super in method?

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.

What is superclass method?

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.


1 Answers

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?

like image 172
Landei Avatar answered Sep 19 '22 08:09

Landei