# Shape Interface Implementation: Java Exercise

EXERCISE: Create a Shape interface having methods area () and perimeter (). Create 2 subclasses, Circle and Rectangle that implement the Shape interface. Create a class Sample with main method and demonstrate the area and perimeters of both the shape classes. You need to handle the values of length, breath, and radius in respective classes to calculate their area and perimeter.

SOLUTION:

In the below program, both the classes Rectangle and Circle implement the shape interface. They override both the methods area and perimeter and define them.

The Rectangle class uses a constructor to receive the values of length and breadth from outside of the class (from test Sample class). Similarly, the Circle class also uses a constructor to receive value of radius.

The shape classes will use their respective area and perimeter mathematical formula.

JAVA CODE:

``````interface Shape {
double area();
double perimeter();
}

class Rectangle implements Shape {

private double length;

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

@Override
public double area() {

}

@Override
public double perimeter() {

return 2 * (length + breadth);
}
}

class Circle implements Shape {

}

@Override
public double area() {

}

@Override
public double perimeter() {

return 2 * Math.PI * radius;
}
}
``````

TEST CLASS:

``````public class Sample {

public static void main(String[] args) {
// Rectangle area and parameter
double length = 2.0;
Rectangle r = new Rectangle(length, breadth);

System.out.println("Rectangle - Area: " + r.area());
System.out.println("Rectangle - perimeter: " + r.perimeter());

// Circle area and parameter
System.out.println("Circle - Area: " + c.area());
System.out.println("Circle - perimeter: " + c.perimeter());

}
}
``````

Output:

``````
Rectangle - Area: 6.0
Rectangle - perimeter: 10.0
Circle - Area: 12.566370614359172
Circle - perimeter: 12.566370614359172
``````