public class Figure {
enum Shape {RECTANGLE, CIRCLE};
final Shape shape;
//These fields are only used if shape is RECTANGLE
double length;
double width;
//This field is only used if shape is CIRCLE
double radius;
//Circle constructor
Figure(double radius) {
shape = Shape.CIRCLE;
this.radius = radius;
}
//Rectangle constructor
Figure(double length, double width) {
shape = Shape.RECTANGLE;
this.length = length;
this.width = width;
}
double area() {
switch (shape) {
case RECTANGLE:
return length * width;
case CIRCLE:
return Math.PI * (radius * radius);
default:
throw new AssertionError(shape);
}
}
}
abstract class Figure {
abstract double area();
}
class Circle extends Figure {
final double radius;
Circle(double radius) {
this.radius = radius;
}
@Override
double area() {
return Math.PI * (radius * radius);
}
}
class Rectangle extends Figure {
final double length;
final double width;
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
double area() {
return length * width;
}
}
Recommended Posts