Shapes calculator
Use inheritance to store various shapes and do calculations on them depending on the type.
abstract class Shape {
abstract double getArea();
abstract double getPerimeter();
}
class Circle extends Shape {
double radius;
Circle(double radius) {
this.radius = radius;
}
double getArea() {
return Math.PI * Math.pow(radius, 2);
}
double getPerimeter() {
return 2 * Math.PI * radius;
}
}
class Rectangle extends Shape {
double length, width;
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
double getArea() {
return length * width;
}
double getPerimeter() {
return 2 * (length + width);
}
}
public class Main {
public static void main(String[] args) {
Circle circle = new Circle(5);
System.out.println("Circle Area: " + circle.getArea());
System.out.println("Circle Perimeter: " + circle.getPerimeter());
Rectangle rectangle = new Rectangle(4, 5);
System.out.println("Rectangle Area: " + rectangle.getArea());
System.out.println("Rectangle Perimeter: " + rectangle.getPerimeter());
}
}
Main.main(null);
Circle Area: 78.53981633974483
Circle Perimeter: 31.41592653589793
Rectangle Area: 20.0
Rectangle Perimeter: 18.0