Thursday, July 8, 2021

Default methods

 

 

 

 

A method in the interface that has a predefined body is known as the default method. It uses the keyword default. default methods were introduced in Java 8 to have 'Backward Compatibility in case JDK modifies any interfaces. 

 

In case a new abstract method is added to the interface, all classes implementing the interface will break and will have to implement the new method. 

 

With default methods, there will not be any impact on the interface implementing classes. default methods can be overridden if needed in the implementation. Also, it does not qualify as synchronized or final.

 

Default methods are declared using the new default keyword. These are accessible through the instance of the implementing class and can be overridden.

@FunctionalInterface // Annotation is optional 
public interface Foo() { 
// Default Method - Optional can be 0 or more 
public default String HelloWorld() { 
return "Hello World"; 
} 
// Single Abstract Method 
public void bar(); 
}

 

 This feature will help us in extending interfaces with additional methods, all we need is to provide a default implementation.

 

 

 Most Important Examples:


Scenerio1:

What if our class is implementing 2 interfaces and both of them have same default method.

Solution:

There can be 2 solution to this problem like below:


public interface Circle { default void print() { System.out.println("I am a circle!"); } }
public interface Square {

   default void print() {
      System.out.println("I am a Square!");
   }
}

 

 

First solution is to create an own method that overrides the default implementation.

 
 
public class Shape implements Circle, Square { public void print() { System.out.println("I am neither circle nor a square but I am a rectangle!"); } }

Second solution is to call the default method of the specified interface using super.

 

public class Shape implements Circle, Square {

   public void print() {
      Circle.super.print();
   }
}




 

 

 

 

 

 

 

No comments:

Post a Comment