Abstract Class with Constants in Java


Create a Java program to demonstrate an abstract class with a constant variable

  • Shape is an abstract class with a static final constant variable PI and an abstract method calculateArea().
  • Circle and Square are subclasses of Shape and provide implementations for the calculateArea() method based on the specific formulas for calculating the area of a circle and a square.
  • In the Main class, instances of Circle and Square are created, and their calculateArea() methods are called to calculate and print the area of the circle and the square, respectively.

Source Code

abstract class Shape
{    
	static final double PI = 3.14159;// Constant variable for PI
 
	abstract double calculateArea();// Abstract method to calculate area (to be implemented by subclasses)
}
 
class Circle extends Shape
{    
	private double radius;
 
	public Circle(double radius)
	{
		this.radius = radius;
	}
 
	@Override
	double calculateArea()// Implementation of the abstract method to calculate the area of the circle
	{
		return PI * radius * radius;
	}
}
 
class Square extends Shape
{
	private double side;
 
	public Square(double side)
	{
		this.side = side;
	}
 
	@Override
	double calculateArea()// Implementation of the abstract method to calculate the area of the square
	{
		return side * side;
	}
}
 
public class Main
{
	public static void main(String[] args)
	{
		Circle circle = new Circle(5);
		Square square = new Square(4);
 
		System.out.println("Area of the circle : " + circle.calculateArea());
		System.out.println("Area of the square : " + square.calculateArea());
	}
}

Output

Area of the circle : 78.53975
Area of the square : 16.0