Interfaces with Static Factory Methods in Java


Write a Java program to demonstrate the use of an interface with a static factory method

  • The MyInterface interface declares a single method doSomething().
  • Inside the MyInterface interface, a static factory method createInstance() is defined. This method returns an instance of MyConcreteClass, which implements MyInterface.
  • In the InterfaceWithStaticFactoryMethodDemo class, the main method demonstrates how to use the static factory method to create an instance of MyConcreteClass through the interface MyInterface.
  • Once the instance is created, the doSomething() method is called, which prints "MyConcreteClass is doing something".

Source Code

public class InterfaceWithStaticFactoryMethodDemo
{
	public static void main(String[] args)
	{
		MyInterface obj = MyInterface.createInstance();// Use the static factory method to create an instance
 
		obj.doSomething(); // Call the method on the created instance
	}
}
 
interface MyInterface// Define an interface with a static factory method
{
	void doSomething();
 
	static MyInterface createInstance() // Static factory method to create instances
	{
		return new MyConcreteClass();
	}
}
 
class MyConcreteClass implements MyInterface// Create a concrete class that implements the interface
{
	@Override
	public void doSomething()
	{
		System.out.println("MyConcreteClass is doing something");
	}
}

Output

MyConcreteClass is doing something

Example Programs