Subclass Method Overrides Abstract Class Method and Implements Interface In Java


Write a Java program to demonstrate method overriding with a subclass that overrides a method from an abstract class and implements an interface

The code defines an interface Drawable with a method draw, an abstract class Shape that implements the Drawable interface and provides a default implementation for the draw method, and a concrete subclass Circle that extends the Shape class and overrides the draw method. Here's an explanation of the code:

  • Drawable is an interface with a single method draw.
  • Shape is an abstract class that implements the Drawable interface by providing a concrete implementation for the draw method. In this default implementation, it prints "Drawing a shape" to the console.
  • Circle is a concrete subclass of Shape. It overrides the draw method to provide its specific implementation, printing "Drawing a circle" to the console.
  • In the Main class, you create an instance of the Circle class using Circle circle = new Circle();.
  • You then call the draw method on the circle object, which invokes the overridden draw method in the Circle class. As a result, "Drawing a circle" is printed to the console.

The use of the Drawable interface and the Shape abstract class allows for method overriding and polymorphism, and your code effectively demonstrates this. When you run the code, it will produce the output "Drawing a circle" as expected.

Source Code

interface Drawable
{
    void draw();
}
 
abstract class Shape implements Drawable
{
    @Override
    public void draw()
	{
        System.out.println("Drawing a shape");
    }
}
 
class Circle extends Shape
{
    @Override
    public void draw()
	{
        System.out.println("Drawing a circle");
    }
}
 
public class Main
{
    public static void main(String[] args)
	{
        Circle circle = new Circle();
        circle.draw();
    }
}

Output

Drawing a circle