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.
No you don't need to provide implementation of default interface methods in implementing class.
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.
In addition to declaring default methods in interfaces, Java 8 also allows us to define and implement static methods in interfaces.
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.
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
}
}
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