Java/[inflearn] 자바 중급(1)

[김영한_자바중급][1. Object클래스] (보충) 다형적 참조 + 메서드 오버라이딩 이해 복습(p.16)

줌인. 2024. 4. 16. 14:35

▶ 다형성1 : 다형적 참조 + 메서드 오버라이딩

https://zoooom-in.tistory.com/70

 

[김영한_자바기본][10. 다형성1] (보충) 다형성과 캐스팅 / 일시적 다운 캐스팅 (p.7-10)

▶ [다형성1] 상속과 메모리 구조 https://zoooom-in.tistory.com/61 [김영한_자바기본][10. 다형성1] 상속과 메모리 구조(p.1-23) 1. 자식 객체를 부모 참조 변수에 할당하면 부모 메서드에 접근이 가능하다. 2.

zoooom-in.tistory.com

 

[자바 기본 / 다형성1_p.16]

package poly.basic;
public class CastingMain5 {
    public static void main(String[] args) {
        Parent parent1 = new Parent();
        System.out.println("parent1 호출");
        call(parent1);
        
        Parent parent2 = new Child();
        System.out.println("parent2 호출");
        call(parent2);
    }
    
    private static void call(Parent parent) {
        parent.parentMethod();
        if (parent instanceof Child) {
            System.out.println("Child 인스턴스 맞음");
            Child child = (Child) parent;
            child.childMethod();
        }
    }
}
상기 코드 접근 로직 설명
1. Child는 Parent를 통해서 상속받음
2. 이에 따라 Child내부를 들어가보면 2가지 인스턴스가 존재한다.
     > 왜? Parent를 상속받았기 때문
3. Parent poly = new Child()일 경우 child의 2가지 인스턴스 중 parent에 접근
     > 왜? 변수타입 자체가 Parent니까
4. 여기서 if (parent instanceof Child)를 살펴보면, parent는 2번에 따라 Child의 인스턴스가 맞기 때문에 참으로 실행됨
5. 따라서 parent가 상속받은 child타입에 접근하기 위해서는 다운캐스팅을 해야함
6. 다운 캐스팅을 위해 Child child = (Child) Parent로 다운캐스팅하면 child.childMethod()에 접근가능하다.

 

 


 

[p.19 / ObjectPolyExample1]

public class ObjectPolyExample1 {

    public static void main(String[] args) {
        Object dog = new Dog();
        Object car = new Car();
        action(dog);
        action(car);

    }
    private static void action(Object obj) {
        if (obj instanceof Dog) {
            Dog dog = (Dog) obj;
            dog.sound();
        } else if (obj instanceof Car car) {
            car.move();
        }
    }
}

 

<다운 캐스팅 종류> : 다운캐스팅화 할 시 참고할 것

private static void action(Object obj) {
    if (obj instanceof Dog) {
        Dog dog = (Dog) obj;
        dog.sound();
    } else if (obj instanceof Car car) {
        car.move();
    }
}
if 구문 else if 구문
일반적인 방식으로 캐스팅을 수행
- obj가 Dog 클래스의 인스턴스인지 확인한 후
   (Dog) obj와 같이 명시적으로 Dog 타입으로 캐스팅
 Java 14부터 도입된 instanceof와 다운캐스팅
- instanceof 연산자와 함께 다운캐스팅을 한 번에 수행
728x90