Subclass Method Overrides Abstract Class Method In Java


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

The code defines an abstract class Shape with an abstract method draw, and a concrete subclass Circle that extends the Shape class by providing an implementation for the draw method. In the Main class, you create an instance of the Circle class and invoke the draw method to print "Drawing a circle" to the console. Here's an explanation of the code:

  • Shape is an abstract class with an abstract method draw. Abstract classes can have abstract methods that must be implemented by concrete subclasses.
  • Circle is a concrete subclass of Shape. It overrides the draw method and provides an implementation that prints "Drawing a circle" to the console.
  • In the Main class, you create an instance of the Circle class using Circle circle = new Circle();. This is possible because Circle is a concrete subclass of Shape.
  • 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.

Source Code

abstract class Shape
{
    abstract void draw();
}
 
class Circle extends Shape
{
    @Override
    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