Default Methods in Interface - Java 8

Java interfaces use to have only abstract methods thanks to JDK 8 that allows the interface to add default and static methods.

During the application enhancement or maintenance, it may possible that new methods are required to be added in an interface that forced all implemented classes to be changed and implement new abstract methods.

Thus we can add these default methods to existing interfaces without breaking the code and changing old implementation classes.

interface DefaultMethod {
 public default void defMethod(){
   System.out.println("Default Method");
 }
}
public class TestDefault{
  public static void main(String[] args) { 
   TestDefault t = new TestDefault(); 
    t.defMethod(); 
  }
}

Likewise, you can define default static methods in an interface with the restriction of not overriding static methods.

Comments

  1. Can anyone help me understand the diamond problem and 'Third Rule' of java problem emerged due to default method addition in interfaces???

    ReplyDelete

Post a Comment

Popular posts from this blog

Java Streams API - Process set of elements

Lambda Expressions

Java 8 Vs Java 9