// Tagged class - vastly inferior to a class hierarchy!classFigure{enum Shape { RECTANGLE, CIRCLE };// Tag field - the shape of this figurefinal Shape shape;// These fields are used only if shape is RECTANGLEdouble length;double width;// This field is used only if shape is CIRCLEdouble radius;// Constructor for circleFigure(double radius){
shape = Shape.CIRCLE;this.radius = radius;}// Constructor for rectangleFigure(double length,double width){
shape = Shape.RECTANGLE;this.length = length;this.width = width;}doublearea(){switch(shape){case RECTANGLE:return length * width;case CIRCLE:return Math.PI *(radius * radius);default:thrownewAssertionError(shape);}}}
继承
// Class hierarchy replacement for a tagged classabstractclassFigure{abstractdoublearea();}classCircleextendsFigure{finaldouble radius;Circle(double radius){this.radius = radius;}@Overridedoublearea(){return Math.PI *(radius * radius);}}classRectangleextendsFigure{finaldouble length;finaldouble width;Rectangle(double length,double width){this.length = length;this.width = width;}@Overridedoublearea(){return length * width;}}