태그달린 클래스는 두개이상의 의미를 표현할 수 있으며, 현재 표현하는 의미를 태그값(일반적으로는 멤버변수 중 하나)으로 알려주는 클래스를 말한다.
class Figure {
enum Shape { RECTANGLE, CIRCLE };
//태그 필드 - 현재 모양을 나타낸다.
final Shape shape;
double length;
double width;
double radius;
Figure(double radius) {
shape = Shape.CIRCLE;
this.radius = radius;
}
Figure(double length, double width) {
shape = Shape.RECTANGLE;
this.length = length;
this.width = width;
}
double area() {
switch(shape) {
case RECTANLGE: 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 * length;
}
}
태그달린 클래스의 단점을 모두 날려버린, 간결하고, 명확하며, 쓸데없는 코드가 사라짐.
- 타입이 의미별로 따로 존재하니 변수의 의미를 명시하거나 제한할 수 있다.
- 타입 사이의 자연스러운 계층 관계를 반영할 수 있어서 유연성과 타입검사능력을 높여줌.