Tuesday, 4 February 2025

Write a Java program for calculating the area of shapes (circle and rectangle) using interfaces.


Using Constructor

// Interface declaration

interface Shape {

    double area();  // Abstract method to calculate area

}

// Circle class implementing Shape interface

class Circle implements Shape {

    double radius;

    // Constructor to initialize radius

    Circle(double radius) {

        this.radius = radius;

    }

    // Implementation of area method

    public double area() {

        return Math.PI * radius * radius;

    }

}

// Rectangle class implementing Shape interface

class Rectangle implements Shape {

    double length, width;

    // Constructor to initialize length and width

    Rectangle(double length, double width) {

        this.length = length;

        this.width = width;

    }

    // Implementation of area method

    public double area() {

        return length * width;

    }

}

// Main class to demonstrate functionality

public class ShapeAreaDemo {

    public static void main(String[] args) {

                Shape circle = new Circle(5);

              Shape rectangle = new Rectangle(4, 6);

        // Calculating and printing areas

       System.out.println("Circle Area: " + circle.area());  System.out.println("Rectangle Area: " + rectangle.area());

    }

}

// Using Setter Methods

import java.io.*;

interface Shape1 {

    double area(); 

}

// Circle class implementing Shape1 interface

class Circle implements Shape1

 {

    double radius;

    // Method to set the radius

    public void setRadius(double r) {

        radius = r; 

    }

    // Implementation of area method

    public double area() {

        return Math.PI * radius * radius;

    }

}

// Rectangle class implementing Shape1 interface

class Rectangle implements Shape1 {

    double length, width;

    // Method to set length and width

    public void setDimensions(double l, double w) {

        length = l; 

        width = w;  

    }

    // Implementation of area method

    public double area() {

        return length * width;

    }

}

public class ShapeAreaDemo1 {

    public static void main(String[] args) {

          Circle circle = new Circle(); 

        circle.setRadius(5);

        // Creating a Rectangle object and setting dimensions

        Rectangle rectangle = new Rectangle(); 

        rectangle.setDimensions(4, 6); 

       System.out.println("Circle Area: " + circle.area());

        System.out.println("Rectangle Area: " + rectangle.area());

    }

}