Item 23. Subtyping

νƒœκ·Έ 달린 ν΄λž˜μŠ€λ³΄λ‹€λŠ” 클래슀 계측ꡬ쑰λ₯Ό ν™œμš©ν•˜λΌ

νƒœκ·Έ 달린 ν΄λž˜μŠ€λž€, ν•˜λ‚˜μ˜ ν΄λž˜μŠ€κ°€ μ—¬λŸ¬κ°€μ§€ κΈ°λŠ₯을 μˆ˜ν–‰ν•˜λŠ” 것을 λ§ν•œλ‹€.

class Figure {
    // νƒœκ·Έ ν•„λ“œ - ν˜„μž¬ λͺ¨μ–‘ μ •μ˜
    final Shape shape;

    // μ‚¬κ°ν˜•(RECTANGLE)일 λ•Œλ§Œ μ‚¬μš©ν•˜λŠ” ν•„λ“œ
    double length;
    double width;
    // λͺ¨μ–‘이 원(CIRCLE)일 λ•Œλ§Œ μ‚¬μš©ν•˜λŠ” ν•„λ“œ
    double radius;

    // CIRCLE νƒœκ·Έλ₯Ό μœ„ν•œ μƒμ„±μž
    Figure(double radius) {
        shape = Shape.CIRCLE;
        this.radius = radius;
    }

    // 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(shape);
        }
    }

    enum Shape {RECTANGLE, CIRCLE}
}

μœ„ μ½”λ“œλ₯Ό 보면 ν•˜λ‚˜μ˜ ν΄λž˜μŠ€κ°€ νƒœκ·Έ ν•„λ“œμ— 따라 μ—¬λŸ¬κ°€μ§€ κΈ°λŠ₯을 μˆ˜ν–‰ν•˜κ³  있으며, λΆˆν•„μš”ν•œ μ½”λ“œκ°€ λ§Žμ•„ λ©”λͺ¨λ¦¬ 낭비와 가독성이 떨어진닀.

Subtyping(ν•˜μœ„ νƒ€μž…)

μœ„μ²˜λŸΌ νƒœκ·Έ ν•„λ“œλ₯Ό μ‚¬μš©ν•˜λŠ” 것이 μ•„λ‹ˆλΌ 계측 ꡬ쑰λ₯Ό ν™œμš©ν•˜λŠ” μ„œλΈŒνƒ€μ΄ν•‘μ„ μ‚¬μš©ν•˜λ©΄ 더 λ‚˜μ€ μ½”λ“œλ₯Ό μž‘μ„±ν•  수 μžˆλ‹€.

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;
    }
}

κΈ°μ‘΄ μ½”λ“œμ™€ 비ꡐ해보면 μ–ΈκΈ‰λœ 단점이 λͺ¨λ‘ ν•΄κ²°λ˜μ—ˆμŒμ„ μ•Œ 수 μžˆλ‹€. λ˜ν•œ ν™•μž₯μ„± λ©΄μ—μ„œ, μƒˆλ‘œμš΄ λͺ¨μ–‘이 μΆ”κ°€λ˜λ”λΌλ„ κΈ°μ‘΄ μ½”λ“œλ₯Ό κ±΄λ“œλ¦΄ ν•„μš”κ°€ μ—†λ‹€.

Last updated

Was this helpful?