4

Consider the following:

//Fooable.java
public interface Fooable {
    public default void foo() {
        System.out.println("Fooable::foo");
    }
    //Lots of other non-default methods...
}

//MyFooable.java
public class MyFooable implements Fooable {
    @Override
    public void foo() {
        System.out.println("MyFooable::foo");
    }
    //implements other methods in Fooable...
}

//MyAdvancedFooable.java
public class MyAdvancedFooable extends MyFooable {
    @Override
    public void foo() {
        Fooable.super.foo();
        System.out.println("MyAdvancedFooable::foo");
    }
    public static void main(String[] args) {
        new MyAdvancedFooable().foo();
    }
}

As you can see, I want to call foo() in Fooable from MyAdvancedFooable (a subclass of MyFooable). However, when I try to compile, I get the following error:

MyAdvancedFooable.java:4: error: not an enclosing class: Fooable Fooable.super.foo();

if I try MyAdvancedFooable extends MyFooable implements Fooable I get the following:

MyAdvancedFooable.java:4: error: bad type qualifier Fooable in default super call Fooable.super.foo(); method foo() is overridden in MyFooable

How can I resolve this problem without having to create a new anonymous implementation of Fooable?

Sina Madani
  • 1,246
  • 3
  • 15
  • 27

3 Answers3

3

You can only call a method one level up so you would need

Fooable.super.foo();

in MyFooable, while just calling super.foo() in MyAdvancedFooable

Reimeus
  • 158,255
  • 15
  • 216
  • 276
1

You can do MyAdvancedFooable extends MyFooable implements Fooable. Then create another interface, AnotherFooable, for example, instead of Fooable, as follows:

public interface AnotherFooable implements Fooable {
    public default void foo() {
        Fooable.super.foo();
    }
}

public class MyAdvancedFooable extends MyFooable implements AnotherFooable {
    @Override
    public void foo() {
        AnotherFooable.super.foo();
        System.out.println("MyAdvancedFooable::foo");
    }
}

See: Create another interface

Fan Zhou
  • 11
  • 2
0

You need to use just super.foo() or this.super.foo() as it is the parent of the object and not of the class as implied by Fooable.super.foo().

Shakhar
  • 432
  • 3
  • 12
  • 1
    The OP wants to call the `foo()` method from the interface. Your solution would call the method in `MyFooable` instead – Robin Topper May 01 '17 at 12:23