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?
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
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
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