if you changes some thing in interface, means add some more methods
The class which previously implementing the interface needs to be updated
But with the help of default method in interface you need not to change the old class which previously implementing the interface
Means that you are providing the default implementation of a method in the interface, default keyword is used before the method signature
The class which implementing it will have the method definition provided in the interface.
Extending interface that contains Default Method
you have 3 option for it
The class which previously implementing the interface needs to be updated
But with the help of default method in interface you need not to change the old class which previously implementing the interface
Means that you are providing the default implementation of a method in the interface, default keyword is used before the method signature
The class which implementing it will have the method definition provided in the interface.
Extending interface that contains Default Method
you have 3 option for it
- Not mention the default method at all, which lets your extended interface inherit the default method.
- Redeclare the default method, which makes it
abstract. - Redefine the default method, which overrides it.
If you redefine it the class which implements new interface will have only access to overridden method
Now what will happen if a class implements both interface???
You cannot implement multiple interfaces having same signature of Java 8 default methods (without overriding explicitly in child class)
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();
}
}
Static Method in the interfaces
Apart from default method you can also have static method, as static method does not needs the instance of class so you can also have static methods in the interfaces also.
You can also have Enums in the interfaces
Note-
if you have simple method in two interfaces and you are implements both interface, You can do it with no error and references of both the interface will able to call method defined in implementing class.
if you have two interfaces with the same method signature
and you have an another interfaces which extends both interface
then at this moment you have no problem
But if you have two methods in both previous scenario which have different return types will result in to Compile time error same issue for method overriding.
Comments
Post a Comment