public class Figure {
enum Shape {RECTANGLE, CIRCLE};
final Shape shape;
//Ces champs ne sont utilisés que si la forme est RECTANGLE
double length;
double width;
//Ce champ n'est utilisé que si la forme est CERCLE
double radius;
//Constructeur de cercle
Figure(double radius) {
shape = Shape.CIRCLE;
this.radius = radius;
}
//Constructeur rectangulaire
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