Why do we need default method in Java 8 interface?

Uttam Pasare
Javarevisited
Published in
2 min readOct 7, 2023

Hello readers,

In general development practices an interface can be implemented by multiple interfaces where implementing classes will be forced to provide implementations for all the abstract methods in an interface.

Adding one or more new methods to interface will result in all the implementing classes will have to provide implementation for new method which creates a major issue while maintaining backward compatibility. This problem usually occurs in java version prior to java 8.

To solve this problem java 8 has introduced a concept of default method in an interface. default methods are public in nature, so we don't have to explicitly provide public keyword. it is possible to provide implementation in default method the way we provide in class level methods.

Lets look at example of default method,

IShape interface has default method defined with print statement and Square class is implementing IShape. If you look at output below which is allowing us to call calculate method using an interface reference.

public interface IShape {
public void draw();

default void calculate() {
System.out.println("IShape default method invoked");
}
}
public class Square implements IShape {

@Override
public void draw() {
System.out.println("Draw a Square!!");
}

}
IShape iShape = new Square();
iShape.draw();
iShape.calculate();

Output ---
Draw a Square!!
IShape default method invoked

If a class is implementing multiple interfaces where both interfaces has methods with same name, then implementing class should explicitly specify which interface method to invoke.

public class Square implements IShape, IShape2 {

@Override
public void draw() {
System.out.println("Draw a Square!!");
}

@Override
public void calculate() {
IShape2.super.calculate();
}

}

Since we have overridden default method and given reference of IShape2, the output will be as below

Draw a Square!!
IShape 2 default method invoked

Does java 8 interfaces same as abstract classes as interface has implementation now?

The answer is No, abstract classes can have abstract as well as concrete methods and member variables.

Conclusion:

default methods are concrete methods which are dependent on abstract method. also, it gives us compatibility to avoid impact on existing implementing classes even if they are kept untouched. This is not replacement of abstract classes in java rather it's an enhancement to solve problems with older version of java.

Example:

above example is available at https://github.com/uttam-pasare/java-features.git

Follow for more — www.linkedin.com/in/uttam-pasare

--

--

Uttam Pasare
Javarevisited

Hello, This is Uttam Pasare working as a Java Professional, love to explore, learn & share knowledge around software technologies.