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?