Java 8: Default Methods in Interface

Java 8 introduces a new concept of Default Methods implementation in interfaces, which allows developer to add new methods to the interfaces without breaking the existing implementation of these interface. So that you can add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces.

public interface Color {
	default void print() {
		System.out.println("From Color");
	}
}

This is also useful when you don’t want to implement some method from interface while implementing in Class.

Ohh no, what if your class have implemented two interfaces and both interfaces have same method “print()”. This may lead to a problem of Ambiguity in Multiple Inheritance.

Default Method: Multiple Inheritance Ambiguity

The code will fail to compile if ambiguity occur, So that you have to specify your own implementation in your class. If we want to invoke default implementation provided by any of super interface rather than our own implementation, then we can do that by using super keyword. For Example,


public interface Shape {
	default void print() {
		System.out.println("From Shape");
	}
}

public interface Color {
	default void print() {
		System.out.println("From Color");
	}
}

public class RedSquare implements Shape,Color {
	@Override
	public void print() {
		Shape.super.print();
	}
}

Difference between Abstract Class and Interface

If Interface provides default implementation then what difference remains between Interface and Abstract Class.

  • Abstract class can define constructor
  • Abstract classes are more structured and have difference states.

Static Default Methods in Interface

If we declare as static methods, then we would regard them as utility methods, not as essential, core methods.


public interface Color {
	default void print() {
		System.out.println("I am Color");
	}
}

public class MainClass{
	public static void main(String[] args) {
		Color.print();
	}
}

Default Methods in Interface are long awaited and much sought out feature of Java 8 because it enables us to add new methods in interface without interfering Implementations of Class.
For more details refer Official Java Documentation: Default Methods

Leave a Reply

Your email address will not be published. Required fields are marked *