Abstract Class & Method in Java


Write a Java program to demonstrate the concept of an abstract class and an abstract method

  • The Shape class is declared as abstract, with an abstract method draw().
  • The Circle and Rectangle classes extend the Shape class and provide their own implementation of the draw() method by overriding it.
  • In the Main class, objects of type Shape are created, initialized with instances of Circle and Rectangle.
  • When calling the draw() method on these objects, the overridden version of the method in the respective subclass (Circle or Rectangle) is invoked, resulting in the appropriate message being printed based on the type of shape.

Source Code

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

Output

Drawing Circle
Drawing Rectangle