본문 바로가기
프로그래밍/JAVA

22 Casting(Up casting/Down casting)과 instanceof

by 윤지(●'◡'●) 2021. 4. 13.
반응형

 


Casting(형변환)

 

형변환은 변수의 자료형을 다른 자료형으로 변환하는 것을 말한다.

자바에서는 기본타입의 변수(int..)뿐만 아니라 객체를 참조하는 변수와

상속 관계 있는 부모 클래스와 자식클래스 간에 형변환이 가능하다. 

상속관계에서의 형변환은 up castingdown casting이 있다.

 

up casting 자식 타입을 부모 타입으로 형변환
down casting up casting된 객체를 자식 타입으로 복구하는 형변환

※ 부모 타입을 자식 타입으로 형변환하면 오류이다.

 

예제로 한번 살펴 보자 :)

 

 

부모 클래스 : Car

class Car{
	String brand;
	String color;
	int price;
	
	public Car() {;} 
	
	public Car(String brand, String color, int price) {
		super(); 
		this.brand = brand;
		this.color = color;
		this.price = price;
	}
	
	void engineStart() {
		System.out.println("열쇠로 시동 켬");
	}
	void engineStop() {
		System.out.println("열쇠로 시동 끔");
	}
	
}

 

 

자식 클래스 : SuperCar

class SuperCar extends Car{
	String mode;
	
	public SuperCar() {;}
	
	public SuperCar(String brand, String color, int price, String mode) {
		super(brand, color, price);
		this.mode = mode;
	}

	@Override
	void engineStart() {
		super.engineStart();
		System.out.println("음성으로 시동 킴");
	}
	@Override
	void engineStop() {
		System.out.println("음성으로 시동끔");
	}
	
	public void openRoof() {
		System.out.println("지붕 열림");
	}
	public void closeRoof() {
		System.out.println("지붕 닫힘");
	}
}

 

메인 클래스 : Road

public class Road {
	public static void main(String[] args) {
		Car matiz = new Car();
		SuperCar ferrari = new SuperCar();
		
		//up Casting
		Car noOptionFerrari = new SuperCar();
		// 부모			<-	자식
		
		// 부모타입 객체 이므로, 자식메소드 사용 불가 
		noOptionFerrari.engineStart();
		noOptionFerrari.engineStop();
		
		//오류 ※ 부모 타입을 자식 타입으로 형변환하면 오류이다.
		//SuperCar brokenCar = new Car();
		
		//down casting
		SuperCar fulloptionFerrari = (SuperCar)noOptionFerrari;
        //	자식			<-	  up casting된 객체를 자식 타입으로 형변환
    				  
		// down casting으로 인해 자식 메소드가 사용 가능하다
		fulloptionFerrari.openRoof();

	}
} 

 

 

Casting을 사용하는 이유는?

- 자식 타입이 수없이 많을 때 부모 타입 매개변수 한개로 모든 자식을 받을 수 있다. (up casting)

그리고, up casting된 객체를 다시 자식 타입으로 변환하는 down casting을 통해 자식 필드에 모두 접근할 수 있다.

 


instanceof

- 참조변수의 형변환 가능 여부 확인에 사용하며, 가능하면 true를 반환한다.

- 주로 상속 관계에서 부모객체인지 자식객체인지 확인하는데 사용된다.

 

객체명 instanceof 클래스명

 

기본사용방법은 위와 같으며 예제로 한번 살펴보자 :)

 

class A{}
class B extends A{}

public class Test {
	public static void main(String[] args) {
		A a = new A();
		B b = new B();
		
		System.out.println(a instanceof A); // true : a는 자신(class A)의 객체이기때문에 형변환 가능
		System.out.println(b instanceof A); // true : b는 A의 자식객체라, 형변환 가능
		System.out.println(a instanceof B); // false : a는 B의 부모객체라, 형변환 불가
		System.out.println(b instanceof B); // true : b는 자신(class B)의 객체이기때문에 형변환 가능
	}
}
반응형

'프로그래밍 > JAVA' 카테고리의 다른 글

24 내부클래스와 익명클래스  (0) 2021.04.15
23 추상클래스와 인터페이스(interface)  (0) 2021.04.15
21 다형성(Polymorphism)  (0) 2021.04.08
20 상속(inheritance)  (0) 2021.04.08

댓글