-
형변환(타입캐스팅)시에 사용해야할 것이론 2015. 9. 21. 10:38반응형
public class ShapeTest {
private static Shape arrayOfShapes[];
public static void main(String[] args) {
// TODO Auto-generated method stub
init();
drawAll();
Shape s = new Rectangle();
if(s instanceof Triangle){
((Triangle)s).setBase(1); //에러나기 때문에 인스턴스오브로 형변환 검사를 해야함
}
if (s instanceof Rectangle) {
((Rectangle) s).setWidth(10);
System.out.println(((Rectangle) s).getWidth());
}
}
public static void init() {
arrayOfShapes = new Shape[4];
arrayOfShapes[0] = new Rectangle();
arrayOfShapes[1] = new Triangle();
arrayOfShapes[2] = new Circle();
arrayOfShapes[3] = new Cylinder();
}
public static void drawAll() {
for (int i = 0; i < arrayOfShapes.length; i++) {
arrayOfShapes[i].draw();
}
}
};
반응형'이론' 카테고리의 다른 글
인터페이스 (0) 2015.09.22 추상메소드 / 추상클래스 (0) 2015.09.21 동적바인딩 - 타입캐스팅 (0) 2015.09.21 동적바인딩 (0) 2015.09.21 암시적, 명시적 관계 (0) 2015.09.18