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.

You can read here about parameterized constructor in Java.

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;
	private double breadth;

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

	@Override
	public double area() {

		return length * breadth;
	}

	@Override
	public double perimeter() {

		return 2 * (length + breadth);
	}
}

class Circle implements Shape {

	private double radius;

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

	}

	@Override
	public double area() {

		return Math.PI * radius * radius;
	}

	@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;
		double breadth = 3.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
		double radius = 2.0;
		Circle c = new Circle(radius);
		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

Leave a Comment