Abstract vs Concrete Methods in Java


Write a Java program to show that an abstract class can contain concrete methods along with abstract methods

  • The Shape class is declared as abstract with an abstract method calculateArea() and a non-abstract method display().
  • The Circle and Rectangle classes extend the Shape class and provide implementations for the abstract calculateArea() method.
  • Each shape class has its own specific fields (radius for Circle and length and width for Rectangle) and constructors to initialize these fields.
  • In the main method, objects of Circle and Rectangle are created, and their respective methods are invoked to calculate the area and display information about the shape.

Source Code

public class AbstractClassExample
{
	public static void main(String[] args)
	{
		Circle circle = new Circle(5);
		Rectangle rectangle = new Rectangle(4, 6);
 
		System.out.println("Circle Area : " + circle.calculateArea());
		circle.display();
 
		System.out.println("Rectangle Area : " + rectangle.calculateArea());
		rectangle.display();
	}
}
 
abstract class Shape
{    
	abstract double calculateArea();// Abstract method (no body)
 
	void display()
	{
		System.out.println("This is a shape");
	}
}
 
class Circle extends Shape
{
	double radius;
 
	Circle(double radius) // Constructor
	{
		this.radius = radius;
	}
 
	@Override
	double calculateArea()// Implementation of the abstract method
	{
		return Math.PI * radius * radius;
	}
}
 
class Rectangle extends Shape
{
	double length;
	double width;
 
	Rectangle(double length, double width) // Constructor
	{
		this.length = length;
		this.width = width;
	}
 
	@Override
	double calculateArea()// Implementation of the abstract method
	{
		return length * width;
	}
}

Output

Circle Area : 78.53981633974483
This is a shape
Rectangle Area : 24.0
This is a shape