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?