instagram

Default Methods In Java 8

This article is about default methods in java interface. In java 8 we can declare default methods in Interface.

Default Methods

Default method is a method that declare with default keyword instead of abstract keyword. In Java 8 we can declare default method with it’s body in Interface. Default method is useful to provide default implementations.

But Why we need it ?

For example in your core API there is an interface Animal that implemented by 10,000 classes. Now if you want to add one more method in Animal interface, You also need to override it in every 10,000 classes.

To solve this problem in Java 8 you just need to add one default method in interface with default implementation no need to override it in every 10,000 classes.

Example Code

Here in this example we have one interface Car.java with one default method printCarColor();. Here BMW.java class implements Car interface but no need to override it’s default method printCarColor();

Car.java

public interface Car {
 
	public default void printCarColor(){
		System.out.println("NO COLOR");
	}
	
}

BMW.java

public class BMW implements Car {
  //Nothing Here
}

Main.java

public class Main {

	public static void main(String[] args) {		

	      BMW bmw = new BMW();
	      bmw.printCarColor();	  
		
	}

}

Output:

NO COLOR

Share