Write a Java program to demonstrate interface inheritance


This Java program illustrates the use of interfaces and how a class can implement multiple interfaces to provide different sets of behaviors. In this program, there are two interfaces, Drawable and Resizable, and a class called Shape that implements both of these interfaces. The Shape class provides concrete implementations for the methods defined in these interfaces. Here's an explanation of the program:

  • public class Main: This is the main class containing the main method, which serves as the entry point of the program.
  • public static void main(String[] args): The main method is where the program execution starts.
  • Shape shape = new Shape();: An instance of the Shape class is created.
  • shape.draw();: The draw method is called on the shape object.
  • shape.resize();: The resize method is called on the shape object.
  • interface Drawable: This is the Drawable interface, which declares a single method draw.
  • void draw();: The draw method in the Drawable interface is declared without an implementation.
  • interface Resizable: This is the Resizable interface, which declares a single method resize.
  • void resize();: The resize method in the Resizable interface is declared without an implementation.
  • class Shape implements Drawable, Resizable: The Shape class implements both the Drawable and Resizable interfaces. This means it is required to provide concrete implementations for both the draw and resize methods.
  • @Override public void draw(): The Shape class overrides the draw method from the Drawable interface and provides an implementation to print "Drawing the Shape."
  • @Override public void resize(): The Shape class overrides the resize method from the Resizable interface and provides an implementation to print "Resizing the Shape."

In this program, the Shape class implements two interfaces, Drawable and Resizable, which provide different sets of behaviors. When the draw and resize methods are called on an instance of the Shape class, the methods from the implemented interfaces are executed. This allows the Shape class to have the ability to draw and resize, making it a versatile object with multiple behaviors defined by interfaces.


Source Code

public class Main
{
	public static void main(String[] args)
	{
		Shape shape = new Shape();
		shape.draw();
		shape.resize();
	}
}
 
interface Drawable
{
	void draw();
}
 
interface Resizable
{
	void resize();
}
 
class Shape implements Drawable, Resizable
{
	@Override
	public void draw()
	{
		System.out.println("Drawing the Shape");
	}
 
	@Override
	public void resize()
	{
		System.out.println("Resizing the Shape");
	}
}

Output

Drawing the Shape
Resizing the Shape