
Java8 New - Default Methodsjava8 introduces a new concept of default method implementation in interfaces. This capability is added for backward compatability so that old interfaces can be used to leverage lambda expression capability of java8. For example List or Collection interfaces do not have forEach method declaration. Thus adding such method will simply break the collection framework implementations. Java8 introduces default method so that List/Collection interface can have a default implemenation of forEach method and class implementing these interfaces need not to implement the same. Syntax
public interface vehicle {
default void print(){ System.out.println("I am a vehicle!"); } } Multiple Defaults With default functions in interfaces, their is a quite possibility that a class implementing two interfaces with same default methods then how to resolve that ambiguity. Consider the following case.
public interface vehicle {
default void print(){ System.out.println("I am a vehicle!"); } } public interface fourWheeler { default void print(){ System.out.println("I am a four wheeler!"); } } First solution is to create an own method which overrides the default implementation.
public class car implements vehicle, fourWheeler {
default void print(){ System.out.println("I am a four wheeler car vehicle!"); } } Second solution is to call the default method of the specified interface using super.
public class car implements vehicle, fourWheeler {
default void print(){ vehicle.super.print(); } } Static default methods Now interface can also have static helper methods as well from Java8 onwards.
public interface vehicle {
default void print(){ System.out.println("I am a vehicle!"); } static void blowHorn(){ System.out.println("Blowing horn!!!"); } } Default method Example Create the following java program using any editor of your choice in say C:/> JAVA Java8Tester.java
public class Java8Tester{
public static void main(String args[]){ Vehicle vehicle =newCar(); vehicle.print(); } } interface Vehicle{ default void print(){ System.out.println("I am a vehicle!"); } static void blowHorn(){ System.out.println("Blowing horn!!!"); } } interface FourWheeler{ default void print(){ System.out.println("I am a four wheeler!"); } } class Car implements Vehicle,FourWheeler{ public void print(){ Vehicle.super.print(); FourWheeler.super.print(); Vehicle.blowHorn(); System.out.println("I am a car!"); } } Verify the result Compile the class using javac compiler as follows
C:\JAVA>javac Java8Tester.java
Now run the Java8Tester to see the result
C:\JAVA>java Java8Tester
See the result.
I am a vehicle!
I am a four wheeler! Blowing horn!!! I am a car! |