JAVA

[자바] 업캐스팅, 다운캐스팅 / instanceof 연산자

yujin0517 2021. 7. 8. 15:56

캐스팅 : 업캐스팅, 다운캐스팅

일단 캐스팅 타입을 변환하는 것이며 형변환이라고도 한다. 상속관계에 있는 부모, 자식 클래스 간에 형변환이 가능하다. 

 

* 업캐스팅 (자동 타입 변환)

  ->자식 클래스 객체를 부모 클래스 타입으로 변환하는 것. (부모 = 자식;)

public class Person {
	...
}

public class Student extends Person {
	...
}

public static void main(String[] args) {
	
    Student s = new Student();
    Person p = s;   //업캐스팅 
    
}

 

* 다운캐스팅 (강제 타입 변환)

  -> 부모 클래스의 객체를 자식 클래스의 타입으로 변환하는 것. ( 자식 = (자식)부모;)

public class Person{
	...
}

public class Student extends Person {
	...
}

public static void main(String[] args) {

    Person p = new Student();    //업캐스팅, 자식 객체가 실제로 생성됨.
    Student s = (Student)p;   //다운캐스팅, 형변환 연산자 사용됨.
    
}

  * 다운캐스팅의 필수 요건 : 형변환 연산자를 필수로 사용해야 하고, 실제로 생성된 객체는 자식 객체이어야 한다.

 

instanceof

-> 레퍼런스가 가리키는 객체의 타입 식별을 위해 사용되며, 사용법은 '객체 instanceof 클래스'이다. 즉, 이 객체가 선언한 클래스가 자신의 클래스가 맞는지 확인해주는 기능을 한다. 그리고 반환 값은 true 혹은 false이다. 

 

- 연습하기 1

public class Person {
	...
}
public class Student extends Person {
	...
}
public class Researcher extends Person {
	...
}
public class Professor extends Researcher {
	...
}

상속 관계를 그림으로 표현

Person kim = new Student();      //업캐스팅
Person lee = new Professor();    //업캐스팅
Person choi = new Researcher();  //업캐스팅

if (kim instanceof Person)       //true
if (kim instanceof Student)      //true
if (choi instanceof Professor)   //false
if (choi instanceof Person)      //true
if (lee instanceof Researcher)   //true
if (lee instanceof Student)      //false

 

- 연습하기 2

if ("java" instanceof String)  //true
if (3 instanceof int)  //false, 객체에 대한 레퍼런스만 instanseof 사용가능

 

* instanceof와 == 의 차이점

-> instanceof는 상속관계에 있는 객체를 두고 자식 클래스인지 여부를 판별하는 것이고, 다형성과 다운캐스팅 시에 사용된다. 다운캐스팅을 할 때, 형변환에서 일어나는 오류를 확인하기 위해 사용한다.

-> '==' 은 서로 다른 객체의 주소 값이 일치하는지 판별할 때 사용된다. 

 

 

감사합니다!

2021.07.08

'JAVA' 카테고리의 다른 글

[자바] 공격 프로그램 구현해보기  (0) 2021.07.11
[자바] 상속  (0) 2021.07.09
this 레퍼런스  (0) 2021.07.08
static멤버 , non - static 멤버  (0) 2021.07.07
힙/스택 영역 표현 (1)  (0) 2021.07.06