LoginSignup
0

More than 3 years have passed since last update.

タグ付きクラスよりクラス階層を選ぶ

Last updated at Posted at 2020-07-29

タグ付きクラス


public class Figure {

    enum Shape {RECTANGLE, CIRCLE};

    final Shape shape;

    // shapeがRECTANGLEである場合にだけこれらのフィールドは使われる
    double length;
    double width;

    // shapeがCIRCLEである場合にだけこのフィールドは使われる
    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 RECTANGLE:
            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 * width;
    }
}

こちらを参考にさせていただきました。
Effective Java

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0