Choose a class hierarchy from tagged classes

Tagged class


public class Figure {

	enum Shape {RECTANGLE, CIRCLE};

	final Shape shape;

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

}

Rewriting by class hierarchy for tagged classes


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

Choose a class hierarchy from tagged classes
GetInstance () from a @Singleton class in Groovy from Java
Transform from a normal class to a lambda expression
Extract elements in order from a class type ArrayList
Loading classes from Path
Generate JSON from JVM class files to see the hierarchy