DEV Community

Dhanush
Dhanush

Posted on

What is the difference between static and default methods in a Java interface?

Static methods

Static methods in interfaces are methods that belong to the interface itself, not to any instance of a class that implements the interface. They can't be overridden by implementing classes, right? You call them using the interface name, like InterfaceName.staticMethod().

Default methods

Default methods, on the other hand, provide a default implementation that implementing classes can use or override. They were introduced in Java 8 to allow adding new methods to interfaces without breaking existing implementations. So if a class doesn't override a default method, it gets the default behavior.

For example, adding a new method to an existing interface where all existing implementations can use the default until they decide to implement their own.

interface Vehicle {  
// Static method  
static String getEngineInfo() 
{ 
return "Generic Engine"; 
}  

// Default method  
default void honk() 
{ 
System.out.println("Beep!"); 
}  
}  

// Usage  
class Car implements Vehicle {}  
Car car = new Car();  
car.honk();                // Output: Beep! (uses default)  
String info = Vehicle.getEngineInfo(); // Calls static method  
Enter fullscreen mode Exit fullscreen mode

There is no need for getEngineInfo() method or honk() method to override in the implementing classes.
Refer: stackoverflow

Top comments (0)