-
Notifications
You must be signed in to change notification settings - Fork 1
Day 18(21.09.30)
Byeong Gwan Seo edited this page Sep 30, 2021
·
2 revisions
※ 오늘은 전체적으로 배운 내용들을 되짚어보는 날이었기에, 공부하며 이해가 부족했었던 부분을 다시 짚어보고자 한다.
프로그램 실행 도중에 자동으로 타입 변환이 일어나는 것을 말하는데, 아래와 같이 사용된다.
부모클래스 변수 = 자식클래스타입;위와 같이 사용했을 때, 자식은 부모의 특징과 기능을 상속받기 때문에 부모와 동일한 취급을 받게 된다. 아래 예시에서 살펴보자.
public class Child extends Parent{
@Override
public void method2() {
System.out.println("Child-method2()");
}
public void method3() {
System.out.println("Child-method3()");
}
}public class ChildExample {
public static void main(String[] args) {
Child child = new Child();
Parent parent = child; // but, 자동 타입 변환 실행 (Child to Parent)
parent.method1();
parent.method2();
System.out.println(parent == child);
parent.method3(); // 컴파일 에러
}
}Result
Parent-method1()
Child-method2()
true
여기서 parent 참조변수가 Parent 타입이니 당연히 Parnet 인스턴스를 참조하는 것이 맞는 것으로 보일 수 있으나, 위 결과에서 확인할 수 있듯이 parent 뿐만 아니라 child 참조변수도 동일한 인스턴스를 참조하고 있다는 것을 확인할 수 있다. 이렇게 Child 인스턴스가 Parent 변수에 대입되어 자동