Implementing Shape Interface

An interface Shape is defined with a method area() which returns the area of the implementing shape. Create the classes Circle and Rectangle which implement the interface Shape. These classes have attributes which reflect their dimensions (radius for a circle, height and width for a rectangle) which are set by their constructors.

The details of the members of the interface and both the classes are given below:

Interface name: Shape
Member functions/methods:
double area(): returns the area of the implementing shape.

Class name: Circle
Data members/instance variables:
radius: to store radius of the circle in decimal.
Member functions/methods:
Circle(double r) : parameterized constructor to initialize radius=r.
double area(): to calculate area of the circle [area of a circle is 3.14 × radius × radius].

Class name: Rectangle
Data members/instance variables:
length : to store length of the rectangle in decimal.
breadth : to store breadth of the rectangle in decimal.
Member functions/methods:
Rectangle(double l, double b): parameterized constructor to initialize length=l, breadth=b.
double area(): to calculate area of the rectangle [area of a rectangle is length × breadth].

Assume that the Interface Shape has been defined. Using the concept of inheritance, specify the classes Circle and Rectangle giving details of their constructors and double area( ) respectively. The interface, main function and algorithm need NOT be written.

interface Shape{
    public double area();
}
class Circle implements Shape{
    double radius;
    public Circle(double r){
        radius = r;
    }
    public double area(){
        return 3.14 * radius * radius;
    }
}
class Rectangle implements Shape{
    double length;
    double breadth;
    public Rectangle(double l, double b){
        length = l;
        breadth = b;
    }
    public double area(){
        return length * breadth;
    }
}
class InterfaceDemo{
    public static void main(String args[]){
        Circle c = new Circle(2.5);
        System.out.println("Area of circle: " + c.area());
        Rectangle r = new Rectangle(5.0, 2.5);
        System.out.println("Area of rectangle: " + r.area());
    }
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.