Java 8 - Default Methods


Java 8 introduces “Default Method” or (Defender methods) new feature, which allows a developer to add new methods to the
Interfaces without breaking the existing implementation of these Interface.

For example, ‘List’ or ‘Collection’ interfaces do not have ‘forEach’ method declaration. Thus, adding such method will simply break the collection framework implementations.

See how it works :

public interface studentClassOne{

   default void classTest() {
      System.out.println("classTest in studentClassOne");
   }
}

public interface studentClassTwo{

   default void classTest() {
      System.out.println("classTest in studentClassOne");
   }
}
public class student implements studentClassOne, studentClassTwo{
}

The above code will fail to compile with the following error,
java: class student inherits unrelated defaults for classTest() from types studentClassOne and studentClassTwo

In order to fix this class, we need to provide default method implementation with super Interface:

public class student implements studentClassOne, studentClassTwo{

   default void classTest() {
      vehicle.super.classTest();
   }
}

Why we needed to implements the default method?

Re-engineering an existing JDK framework is always very complex.If we modify one interface in JDK interface in JDK
framework breaks all classes and extends the interface ,when we want to adding any new method could be break millions of code.
Therefore Defaults method has introduced in Java 8.


Default methods can be provide to an interface without affecting implementaing calsses as it includes an implementation.

No comments: