Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to call super().super() in overridden method (grandparent method) [duplicate]

Tags:

Possible Duplicate:
Why is super.super.method(); not allowed in Java?

I have 3 classes they inherit from each other as follows:

A
 ↳
   B
    ↳
     C

Inside each class I have the following method:

protected void foo() {
    ...
}

Inside class C I want to call foo from class A without calling foo in B:

protected void foo() {
    // This doesn't work, I get the following compile time error:
    // Constructor call must be the first statement in a constructor
    super().super().foo(); 
}

EDIT
Some Context Info:
Class B is an actual class we use. Class C is a unit test class, it has some modifications. foo method inside B does some things we don't want so we override it inside C. However foo in class A is useful and needs to be called.

like image 782
Caner Avatar asked Aug 13 '12 14:08

Caner


People also ask

When to use Super to call an overridden method in Java?

Using Super to call an Overridden Method — AP CSA Java Review - Obsolete 11.9. Using Super to call an Overridden Method ¶ Sometimes you want the child class to do more than what a parent method is doing. You want to still execute the parent method, but then do also do something else.

How to call a method in a super class?

However foo in class A is useful and needs to be called. Show activity on this post. To call a method in a super class, you use super.foo (), not super ().foo (). super () calls the constructor of the parent class. There is no way to call super.super.foo ().

How to override the method of the parent class in Java?

The object of the class GFG calls a method with a String Parameter. If both parent & child classes have the same method, then the child class would override the method available in its parent class. By using the super keyword we can take advantage of both classes (child and parent) to achieve this.

Why does the keyword super stick in Java?

The keyword superdoesn't "stick". Every method call is handled individually, so even if you got to SuperClass.method1()by calling super, that doesn't influence any other method call that you might make in the future.


2 Answers

  • To call a method in a super class, you use super.foo(), not super().foo(). super() calls the constructor of the parent class.
  • There is no way to call super.super.foo(). You can add a call to super.foo() in class B, so that calling super.foo() in C, will call super.foo() in B which in turn will call foo() in A.
like image 95
assylias Avatar answered Sep 24 '22 03:09

assylias


It's not possible in Java. You'd need to rely on B providing you with an explicit way to access to A's foo.

like image 37
Romain Avatar answered Sep 22 '22 03:09

Romain