Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Java default methods in a subinterface or implementation class

I understand if a class overrides a default method, you can access the default method in the following manner

interface IFoo {
    default void bar() {}
}

class MyClass implements IFoo {
    void bar() {}
    void ifoobar() {
        IFoo.super.bar();
    }
}

But what about the case where an interface overrides a default method? Is the parent method available in any way?

interface IFoo {
    default void bar() {}
}

interface ISubFoo extends IFoo {
    // is IFoo.bar available anywhere in here?
    default void bar {}
} 

class MyClass implements ISubFoo {
    // is IFoo.bar available anywhere in here too?

    public static void main(String[] args) {
        MyClass mc = new MyClass();
        mc.bar(); // calls ISubFoo.bar
    }
}

The verbiage Java uses for default methods is similar to that for classes, otherwise it's confusing/misleading. Subinterfaces "inherit" default methods, and can "overwrite" them. So it seems IFoo.bar should be accessible somewhere.

like image 713
rjh.sgc Avatar asked Nov 01 '22 16:11

rjh.sgc


People also ask

Do default methods have to be implemented Java?

No you don't need to provide implementation of default interface methods in implementing class.

What is default method implementation in Java?

Default methods enable you to add new functionality to existing interfaces and ensure binary compatibility with code written for older versions of those interfaces. In particular, default methods enable you to add methods that accept lambda expressions as parameters to existing interfaces.

Can we declare default methods inside a class in Java?

In addition to declaring default methods in interfaces, Java 8 also allows us to define and implement static methods in interfaces.

How will you call a default method of an interface in a class?

A class can override a default interface method and call the original method by using super , keeping it nicely in line with calling a super method from an extended class. But there is one catch, you need to put the name of the interface before calling super this is necessary even if only one interface is added.


1 Answers

You can go one level up, so the IFoo.bar() is available in ISubFoo with IFoo.super.bar().

interface IFoo {
    default void bar() {}
}

interface ISubFoo extends IFoo {
    // is IFoo.bar available anywhere in here?
    // Yes it is
    default void bar {
        IFoo.super.bar()
    }
} 

class MyClass implements ISubFoo {
    // is IFoo.bar available anywhere in here too?
    // Not it is not

    public static void main(String[] args) {
        MyClass mc = new MyClass();
        mc.bar(); // calls ISubFoo.bar
    }
}
like image 192
Erwin de Gier Avatar answered Nov 11 '22 06:11

Erwin de Gier