몬그로이

다형성(Polymorphism) 본문

Organizing Docs/Java Docs

다형성(Polymorphism)

Mon Groy 2024. 5. 23. 20:00
Parent parent1 = new Parent(); 가능
Child child1 = new Child(); 가능
Parent parent2 = new Child(); 가능
Child child2 = new Parent();  불가능
parent1 = (Parent) child2; 업캐스팅
child1 = (Child) parent2; 다운캐스팅 (조심해야 함)
Parent instanceof Child false
Child instanceof Parent true
parent.Childmethod() 불가
child.Parentmethod() 가능

다형적 참조(Polymorphism)

하나의 객체가 다른 타입으로 사용되는 것

상속 받을 수록 구체적이 되므로 자식클래스는 추상적이었던 부모 클래스의 인스턴스가 될 수 없다

반대로 추상적이었던 부모는 구체적인 자식클래스의 인스턴스가 될 수 있다

 

Parent parent = new Parent
parent.method();
Parent 의 method() 사용
Child child = new Child
child.method();
Child 의 method() 사용
Parent poly= new Child
poly.method();
Child 의 method() 사용
Parent poly = new Child
poly.value
Parent 의 value 값 나옴

@Overriding메서드를 재정의 하는 것이다(변수 불포함)

'Organizing Docs > Java Docs' 카테고리의 다른 글

자바의 정석 5. 배열(Array)  (0) 2024.06.18
쓰기 지연 저장소와 지연 로딩  (0) 2024.06.04
Regrex 정규표현식(Regular Expression)  (0) 2024.05.31
JPA - Entity 연관 관계  (0) 2024.05.27
생성자  (0) 2024.05.23