Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Monday, February 24, 2025

Java program that implements inheritance and method overriding

Objective: Write a Java Program to create an abstract class named Shape that contains two integers and an empty method named print Area(). Provide three classes named Rectangle, Triangle and Circle such that each one of the classes extends the class Shape. Each one of the classes contains only the method print Area () that prints the area of the given shape.


Code: 

import java.util.Scanner;

// Base class
abstract class Shape {
    abstract void printArea();  // Abstract method (empty method)
}

// Derived class for Rectangle
class Rectangle extends Shape {
    private double length, breadth;

    Rectangle(double length, double breadth) {
        this.length = length;
        this.breadth = breadth;
    }

    @Override
    void printArea() {
        double area = length * breadth;
        System.out.println("Area of Rectangle: " + area);
    }
}

// Derived class for Triangle
class Triangle extends Shape {
    private double base, height;

    Triangle(double base, double height) {
        this.base = base;
        this.height = height;
    }

    @Override
    void printArea() {
        double area = 0.5 * base * height;
        System.out.println("Area of Triangle: " + area);
    }
}

// Derived class for Circle
class Circle extends Shape {
    private double radius;

    Circle(double radius) {
        this.radius = radius;
    }

    @Override
    void printArea() {
        double area = Math.PI * radius * radius;
        System.out.println("Area of Circle: " + area);
    }
}

// Main class
public class ShapeAreaDemo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Input for Rectangle
        System.out.print("Enter length of the rectangle: ");
        double length = scanner.nextDouble();
        System.out.print("Enter breadth of the rectangle: ");
        double breadth = scanner.nextDouble();
        Shape rectangle = new Rectangle(length, breadth);

        // Input for Triangle
        System.out.print("Enter base of the triangle: ");
        double base = scanner.nextDouble();
        System.out.print("Enter height of the triangle: ");
        double height = scanner.nextDouble();
        Shape triangle = new Triangle(base, height);

        // Input for Circle
        System.out.print("Enter radius of the circle: ");
        double radius = scanner.nextDouble();
        Shape circle = new Circle(radius);

        System.out.println("\nCalculating Areas:");
        rectangle.printArea();
        triangle.printArea();
        circle.printArea();

        scanner.close();
    }
}



Output:



No comments:

Post a Comment