If I have two interface with the same default method and both are implementing with a class/ See this program.
interface alpha {
default void reset() {
System.out.println("This is alpha version of default");
}
}
interface beta {
default void reset() {
System.out.println("This is beta version of default");
}
}
class MyClass implements alpha, beta {
void display() {
System.out.println("This is not default");
}
}
class main_class {
public static void main(String args[]) {
MyClass ob = new MyClass();
ob.reset();
ob.display();
}
}
then what will happen? And also I am getting unrelated error with this program.
If we are using more than one interface and in both interfaces, if both interfaces have the same name and same structure. So at that time, one must override either one both the default method otherwise it will result in an error.
Multiple Defaults With default functions in interfaces, there is a possibility that a class is implementing two interfaces with same default methods. The following code explains how this ambiguity can be resolved. First solution is to create an own method that overrides the default implementation.
Classes can implement more than one interface. As interface can consist of default methods in Java 8, which a class does not necessarily need to implement. We can have two interfaces that have default methods with the same name and signature.
In case both the implemented interfaces contain default methods with same method signature, the implementing class should explicitly specify which default method is to be used or it should override the default method.
You cannot implement multiple interfaces having same signature of Java 8 default methods (without overriding explicitly in child class)
. You can solve it by implementing the method E.g.
class MyClass implements alpha, beta {
void display() {
System.out.println("This is not default");
}
@Override
public void reset() {
//in order to call alpha's reset
alpha.super.reset();
//if you want to call beta's reset
beta.super.reset();
}
}
In effect,these two methods are the same in the class that implements them.If you try to implement the two methods in Intellij for instance, you only get one method. You can't declare the two even if you want to have different signatures for both of them.
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