Write a Java program to demonstrates method overriding


This Java program demonstrates class inheritance and method overriding. It defines two classes, Shape (the parent class) and Circle (the child class), where Circle inherits from Shape. The program calculates the area of a circle using the calculateArea method, which is overridden in the Circle class. Here's an explanation of the program:

  • class Circle extends Shape: This is the Circle class, which extends the Shape class, indicating that it inherits properties and methods from the parent class.
  • double radius: The Circle class has a property called radius to represent the radius of the circle.
  • Circle(double radius): This is the constructor of the Circle class, which takes a radius parameter and sets the radius property accordingly.
  • @Override void calculateArea(): The calculateArea method in the Circle class is marked with the @Override annotation, indicating that it overrides the same method in the parent class. In this method, the area of the circle is calculated using the formula for the area of a circle (π * radius^2), and the result is printed to the console.
  • public static void main(String[] args): This is the main method, the entry point of the program.
  • Circle circle = new Circle(5.0);: It creates an instance of the Circle class with a radius of 5.0.
  • circle.calculateArea();: This line calls the calculateArea method on the circle object, which calculates and prints the area of the circle to the console.
  • class Shape: This is the parent class, which contains a method named calculateArea.
  • void calculateArea(): The calculateArea method in the Shape class is a placeholder method that prints "Area calculation not implemented" to the console.

This program demonstrates inheritance and method overriding. The Circle class inherits the calculateArea method from the parent Shape class and provides its own implementation to calculate the area of a circle. When the calculateArea method is called on a Circle object, it correctly calculates and displays the area of the circle. This showcases the concept of polymorphism in object-oriented programming.


Source Code

class Circle extends Shape
{
	double radius;
 
	Circle(double radius)
	{
		this.radius = radius;
	}
 
	@Override
	void calculateArea()
	{
		double area = Math.PI * radius * radius;
		System.out.println("Area of Circle : " + area);
	}
 
	public static void main(String[] args)
	{
		Circle circle = new Circle(5.0);
		circle.calculateArea();
	}
}
 
class Shape
{
	void calculateArea()
	{
		System.out.println("Area calculation not implemented");
	}
}

Output

Area of Circle : 78.53981633974483