Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call default interface method from another subclass?

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?

like image 579
Sina Madani Avatar asked Oct 14 '25 10:10

Sina Madani


2 Answers

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

like image 85
Reimeus Avatar answered Oct 18 '25 04:10

Reimeus


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

like image 32
Fan Zhou Avatar answered Oct 18 '25 06:10

Fan Zhou



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!