A class that shows two or more types of characteristics and switches between them with tags that have those characteristics in the field is called a tagged class. The following class is an example of this, and it is possible to represent circles and rectangles.
package tryAny.effectiveJava;
class Figure {
enum Shape {
RECTANGLE, CIRCLE
}
//Hold shape type
final Shape shape;
//Use only when shape is RECTANGLE
double length;
double width;
//Use only when shape is CIRCLE
double radius;
//Constructor for circle
Figure(double radius) {
shape = Shape.CIRCLE;
this.radius = radius;
}
//Constructor for rectangle
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();
}
}
}
Such tagged classes have many drawbacks. Below is a list of drawbacks.
If it is an object-oriented language, it can be improved by using a class hierarchy.
The procedure for modifying from a tagged class to a class hierarchy is
The above correction result is as follows.
package tryAny.effectiveJava;
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;
}
}
By doing this, the drawbacks of the tagged class mentioned above are eliminated.
Class hierarchies can reflect the true hierarchical relationships between types, which can improve flexibility (?) And improve compile-time error checking.
When it is decided to add a square type in the above example, it can be described as follows using the characteristics of the class hierarchy.
class Square extends Rectangle {
Square(double side) {
super(side, side);
}
}
Recommended Posts