Default Method in Java

The default method in Interfaces was introduced in Java 8. It allows the interface to implement a method in the interface which is inherited by implementing classes.

What are default methods?

Before Java 8 methods in the interface could have only public and abstract modifiers for methods and public, static and for fields public and static or blank (blank means public and static field).

Java 5

Following are two interfaces in Java 5, the first one is valid and the second one is not.
Valid Interface in Java 5
interface Java5Interface {
	public static int four = 4;
	int five = 5; // implicitly public static

	public abstract void welcome();
	public void sayHi();
	void bye();
}
Invalid Interface in Java 5
interface Java5Invalid {
	private int six = 6;            //illegal only public static and final is permitted
	private void cleanuup(); // illegal only public and abstract is permitted
}
As you can see for fields only public, static, and final modifiers are allowed. If nothing is mentioned then also all fields in Java 5 is public static and final implicitly. For methods, we can have only public and abstract as modifiers.

Java 8 and onwards

Starting Java 8 methods in the interface can have the following modifiers public, private, abstract, default, static, strictfp. Nothing changes for fields, fields can still have public, static, final modifiers. In the following example, we have a Greetings Interface with two default methods greet and openDoor respectively. This interface also has one static method lockdoor.
Interface Greetings in Java 8
interface Greetings {
	
	public default void greet() {
		openDoor();
		sayHi();
		sayBye();
		closeDoor();
	}
	
	default void openDoor() {
		//open the door
	}
	
	void sayHi();
	
	void sayBye();
	
	private void closeDoor() {
		lockDoor();
	}

	static void lockDoor() {
		//lock door implementation
	}
}
The benefit of having a default method is that now the interface can provide a default implementation of methods through the default modifier. For instance, the interface Greetings provided a default implementation for method greet(). Also the later we can add more default, private or static methods to the Interface without breaking binary compatibility meaning implementing classes don't need to do any modification to be able to compile and run successfully.
Importat Points
  • default methods are public.
  • default methods are inherited by implementation classes.
  • default methods can be overridden by implementation classes.
  • a default method can add more functionality to the Interface without breaking binary compatibility.
  • static methods are also allowed which are Interface level methods and cannot be overridden by subclasses.
  • Java 8 methods can have public, private, abstract, default, static, and strictfp.

References