[Java OOP] abstraction2

  • TuanLQ7
  • Easy
  • 100 Points

Task

Write a program to create interface IShape and 2 classes Rectangle, Circle as below:

Explanation:

interface IShape

  • getArea() and getPerimeter() are two abstract methods used for calculating the circumference and area of an object.

Rectangle class

  • length and width attributes describe the length and width of a rectangle.
  • rectangle(length: double, width: double) method initializes values to attributes.
  • getArea() and getPerimeter() methods are overridden from interface IShape, they return the circumference and area of the rectangle.

Circle class

  • radius attibute describes the radius of a circle.
  • Circle(radius: double) method assign values to radius.
  • getArea() and getPerimeter() methods are overridden from interface IShape, they return area and circumference of the circle respectively (π = 3.14).

A program to test the result:

public class Entry {
	public static void main(String[] args) {
		IShape[] shapes = new IShape[3];
		shapes[0] = new Rectangle(3.4, 5.3);
		shapes[1] = new Circle(5.5);
		shapes[2] = new Rectangle(7.4, 4.3);
		for (int i = 0; i < 3; i++) {
			System.out.println("Area of shapes[" + i + "]: " + shapes[i].getArea());
			System.out.println("Perimeter of shapes[" + i + "]: " + shapes[i].getPerimeter());
		}
	}
}

When the above code is compiled and executed, it produces the following result:

Area of shapes[0]: 18.02
Perimeter of shapes[0]: 17.4
Area of shapes[1]: 94.985
Perimeter of shapes[1]: 34.54
Area of shapes[2]: 31.82
Perimeter of shapes[2]: 23.4

Instruction

Code sample:

IShape.java file

public interface IShape {
	double getArea();

	double getPerimeter();
}

Rectangle.java file

public class Rectangle implements IShape {
	private double length;
	private double width;

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

	@Override
	public double getArea() {
		return length * width;
	}

	@Override
	public double getPerimeter() {
		return (length + width) * 2;
	}
}

Circle.java file

public class Circle implements IShape {
	private double radius;

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

	@Override
	public double getArea() {
		return 3.14 * radius * radius;
	}

	@Override
	public double getPerimeter() {
		return 2 * 3.14 * radius;
	}
}