이론

형변환(타입캐스팅)시에 사용해야할 것

박성우기 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();

}

}


};










반응형