- Object Casting
: A extends B
: B b = new A();
: 그런데 여기서 A a = new B();는 안된다.
: 이것을 억지로 해주는 것이 Object Casting이다.
- 예제 소스
public class ObjectCastingTest {
public static void main(String[] args) {
}
}
class SubCastingTest extends ObjectCastingTest{
public void test(){
SubCastingTest sct = new SubCastingTest();
ObjectCastingTest oct = new SubCastingTest();
// SubCastingTest sc = new ObjectCastingTest(); // 이 방법은 안됨
SubCastingTest sc = (SubCastingTest) new ObjectCastingTest(); // ObjectCasting 사용
}
}
- 소스
public class ObjectCastingExam{
public static void main(String args []){
Car car = new Car();
System.out.println("car.Carname="+car.carname+"\n");
EfSonata ef = new EfSonata();
System.out.println("ef.carname="+ef.carname);
Car carTypeEf = new EfSonata();
System.out.println("carTypeEf.carname="+carTypeEf.carname);
System.out.println("carTypeEf intanceof EfSonata = "+(carTypeEf instanceof EfSonata));
EfSonata efSonataFromCarTypeEfSonata = (EfSonata)carTypeEf;
System.out.println("efSonataFromCarTypeEfSonata.carname="+efSonataFromCarTypeEfSonata.carname);
System.out.println("efSonataFromCarTypeEfSonata intanceof EfSonata="+(efSonataFromCarTypeEfSonata instanceof EfSonata));
// Object 캐스팅 = 문법적으로 에러 안남
// 겉모양은 Efsonata이지만 원래는 Car 클래스를 의미
// EfSonata car2ef = (EfSonata)car;
// 레퍼런스 타입이 클래스 타입이 되는지를 비교하는 건데
// car2ef 겉모양은 Efsonata이지만 원래는 Car이기에 Car 클래스가 부모입니다.
// 그래서 Car 클래스는 Efsonata가 될 수 없습니다.
// System.out.println("car2ef instanceof EfSonata = "+(car2ef instanceof EfSonata)); // 부모가 자식이 될 수 없음
System.out.println();
Excel ex = new Excel();
System.out.println("ex.carName="+ex.carname);
Car carTypeExcel = new Excel();
System.out.println("carTypeExcel.carName="+carTypeExcel.carname);
System.out.println("carTypeExcel instanceof Excel = "+(carTypeExcel instanceof Excel));
Excel excelFromCarTypeExcel = (Excel)carTypeExcel;
System.out.println("excelFromCarTypeExcel.carname="+excelFromCarTypeExcel.carname);
System.out.println("excelFromCarTypeExcel instanceof Excel = "+(excelFromCarTypeExcel instanceof Excel));
// Excel car2ex = (Excel)car;
// System.out.println("car2ex instanceof Excel = "+(car2ex instanceof Excel));
System.out.println();
Canival ca = new Canival();
System.out.println("ca.carname="+ca.carname);
Car carTypeCanival = new Canival();
System.out.println("carTypeCanival.carname="+carTypeCanival.carname);
System.out.println("carTypeCanival instanceof Canival = "+(carTypeCanival instanceof Canival));
Canival canivalFromCarTypeCanival=(Canival)carTypeCanival;
System.out.println("canivalFromCarTypeCanival.carname="+canivalFromCarTypeCanival.carname);
System.out.println("canivalFromCarTypeCanival instanceof Canival="+(canivalFromCarTypeCanival instanceof Canival));
// Canival car2ca = (Canival)car;
// System.out.println("car2ca instanceof Canival = "+(car2ca instanceof Canival));
}
}
- 결과