[Java] Choose a class hierarchy from tagged classes

less than 1 minute read

tagged class

``’’ java

public class Figure {

enum Shape {RECTANGLE, CIRCLE};

final Shape shape;

// these fields are used only 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); } }

}


### Class rewriting for tagged classes
``'' java

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;
}
}

Tags:

Updated: