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메서드를 재정의 하는 것이다(변수 불포함)