본문 바로가기
개발 수업/JAVA

[Java] 상속/타입변환(강제 타입 변환(casting),객체 타입 확인(instanceof))

by 오늘 하루s 2023. 5. 18.
728x90
더보기

Day15-1. 230518

타입변환

강제 타입 변환(casting)

- 부모 타입을 자식 타입으로 변환하는 것. 

- 자식 타입이 부모 타입으로 자동 타입 변환 후, 다시 자식 타입으로 변환할 때 강제 타입 변환을 사용 할 수 있음.

자식타입 변수 = (자식타입) 부모타입;
Parent parent = new Child(); //자동 타입 변환
Child child = (Child) parent; //강제 타입 변환

 

 

객체 타입 확인(instanceof)

- 처음부터 부모 타입을 생성된 객체는 자식 타입으로 변환 할 수 없음.

자식 타입 -> 부모 타입으로 변환 되어 있는 상태에서만 가능하기 때문에.

Parent parent = new Child(); 
Child child = (Child) parent; //강제 타입 변환 할 수 없음.

- instanceof 연산자 : 어떤 객체가 어떤 클래스의 인스턴스인지 확인하기 위해 사용

-> 먼저 자식 타입인지 확인 후 강제 타입 실행해야 함.

 

booloan result = 좌향(객체) instanceorf 우향(타입)

- 좌향의 객체가 우향의 인스턴스이면, 즉 우향 타입으로 객체가 생성되었다면 true 리턴, 그렇지 않으면 false리턴

- instanceo f연산자 주로 매개값의 타입 조사할 때 사용.

메소드 내에서 강제 타입 변환이 필요할 경우 반드시 매개값이 어떤 객체인지 instanceof 연산자로 확인하고 안전하게 강제 타입 변환 해야 함.

 

타입 확인하지 않고 강제 타입 변환을 시도한다면 ClassCastException 발생

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package chap0607;
 
class Grandmother01{
    int age = 80;
    void ski() {System.out.println("할머니의 ski()");}
    void drive() {System.out.println("할머니의 차drive()");}
}
class Mother01 extends Grandmother01{
    int age = 50;
    void cook() {System.out.println("엄마의 cook()");}
    @Override
    void drive() {System.out.println("엄마의 배drive()");}
}
class Daughter01 extends Mother01{
    int age = 20;
    void study() {System.out.println("딸의 study()");}
    @Override
    void drive() {System.out.println("딸의 비행기drive()");}
}
 
public class Casting01_p348 {
    public static void main(String[] args) {
        Mother01 m1 = new Daughter01(); //자동타입변환
        System.out.println("m1.age="+m1.age); 
        //자동타입변환된 이후에는 부모클래스애서 선언된 필드와 메서드만 접근 가능.
        m1.cook(); 
        m1.drive(); 
        m1.ski();
        System.out.println();
        
        //객체타입확인(p350) : 참조변수 instanceof 클래스    
        if( m1 instanceof Daughter01) {
            Daughter01 d2 = (Daughter01) m1;
            System.out.println("d2.age="+d2.age);
            d2.cook();
            d2.drive(); 
            d2.ski(); 
            d2.study();
        }
    
        if( m1 instanceof Grandmother01 ) {
            System.out.println("m1참조변수는 할머니01의 인스턴스");
            Grandmother01 gm3=(Grandmother01)m1;
            System.out.println(gm3.age);
        }else {
            System.out.println("m1참조변수는 할머니01의 인스턴스x");
        }    
}
cs
더보기

* 실행 결과

 

m1.age=50
엄마의 cook()
딸의 비행기drive()
할머니의 ski()

d2.age=20
엄마의 cook()
딸의 비행기drive()
할머니의 ski()
딸의 study()
m1참조변수는 할머니01의 인스턴스
80

728x90