public interface Shape {
final double PI = 3.14;
void draw();
double getArea();
default public void redraw() {
System.out.print("--- 다시 그립니다. ");
draw();
}
}
public class Circle implements Shape {
private int radius;
public Circle(int radius) {
// TODO Auto-generated constructor stub
this.radius = radius;
}
@Override
public void draw() {
// TODO Auto-generated method stub
System.out.println("반지름은 "+radius+"인 원입니다.");
}
@Override
public double getArea() {
// TODO Auto-generated method stub
return PI*radius*radius;
}
}
public class Rect implements Shape {
private int width;
private int height;
public Rect(int width, int height) {
// TODO Auto-generated constructor stub
this.width = width;
this.height = height;
}
@Override
public void draw() {
// TODO Auto-generated method stub
System.out.println(width+"x"+height+"크기의 사각형입니다.");
}
@Override
public double getArea() {
// TODO Auto-generated method stub
return width*height;
}
}
public class Oval implements Shape {
private int a,b;
public Oval(int a, int b) {
// TODO Auto-generated constructor stub
this.a = a;
this.b = b;
}
@Override
public void draw() {
// TODO Auto-generated method stub
System.out.println(a+"x"+b+"크기의 사각형입니다.");
}
@Override
public double getArea() {
// TODO Auto-generated method stub
return PI*a*b;
}
}
public class ex12 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Shape [] list = new Shape[3];
list[0] = new Circle(10);
list[1] = new Oval(20,30);
list[2] = new Rect(10,40);
for(int i=0;i<list.length;i++) list[i].redraw();
for(int i=0;i<list.length;i++)System.out.println("면적은 "+list[i].getArea());
}
}
결과
--- 다시 그립니다. 반지름은 10인 원입니다.
--- 다시 그립니다. 20x30크기의 사각형입니다.
--- 다시 그립니다. 10x40크기의 사각형입니다.
면적은 314.0
면적은 1884.0000000000002
면적은 400.0
'명품JAVA프로그래밍 > 5장 상속' 카테고리의 다른 글
[명품JAVA프로그래밍] 5장 실습문제 13번 (0) | 2022.01.17 |
---|---|
[명품JAVA프로그래밍] 5장 실습문제 12번 (0) | 2022.01.17 |
[명품JAVA프로그래밍] 5장 실습문제 11번 (0) | 2022.01.17 |
[명품JAVA프로그래밍] 5장 실습문제 10번 (0) | 2022.01.13 |
[명품JAVA프로그래밍] 5장 실습문제 9번 (0) | 2022.01.13 |