Static & Default Methods in Interfaces in Java


Create a Java program to demonstrate the concept of interfaces with static methods and default methods

  • The MyInterface interface contains a static method staticMethod(), a default method defaultMethod(), and an abstract method abstractMethod().
  • The MyClass class implements the MyInterface interface and provides implementations for the abstract methods.
  • In the main method of InterfaceDemo, we demonstrate calling the static method directly on the interface, calling the default method through an instance of MyClass, and calling the abstract method implemented in MyClass.

Source Code

public class InterfaceDemo
{
	public static void main(String[] args)
	{
		MyInterface.staticMethod();  // Call the static method of the interface
 
		MyClass myClass = new MyClass(); // Create an instance of MyClass
 
		myClass.defaultMethod();// Call the default method of the interface through the instance
 
		myClass.abstractMethod();// Call the abstract method implemented in MyClass
	}
}
 
interface MyInterface
{
	static void staticMethod()// Static method
	{
		System.out.println("This is a static method in MyInterface");
	}
 
	default void defaultMethod()// Default method
	{
		System.out.println("This is a default method in MyInterface");
	}
 
	void abstractMethod(); // Abstract method
}
 
class MyClass implements MyInterface// Implement the interface in a class
{    
	@Override
	public void abstractMethod()// Implement the abstract method
	{
		System.out.println("This is the implementation of the abstract method in MyClass");
	}
 
	@Override
	public void defaultMethod()// You can choose to override the default method if needed
	{
		System.out.println("This is a custom implementation of the default method in MyClass");
	}
}

Output

This is a static method in MyInterface
This is a custom implementation of the default method in MyClass
This is the implementation of the abstract method in MyClass

Example Programs