본문 바로가기
자기개발/정보처리기사(취득)

[정보처리기사] java 다형성 구현 방법

by 램플릿 2024. 4. 15.
다형성 구현 방법


1) 상속 클래스 구현
2) 메소드 오버라이딩
3) 업캐스팅하여 객체 선언
4) 부모 클래스 객체로 자식 메소드 호출

class Parent {
    ...
    void print() {
        System.out.println("Parent");
    }
}


class Child extends Parent {
    ...
    void print(){
        System.out.println("Child");
    }
}

Parent p = new Child();

p.print(); 

        의 결과는 ?

=> 부모클래스로 객체를 선언했으나 실행 시점에 동적 바인딩(실행시점에서 메서드의 성격이 결정되는 바인딩) 되어 자식클래스의 멤버함수가 호출된다. = Child

 

 

 

객체 타입 확인 방법

 

if(p instanceof Child) {   p.print();   } //true

 

 

출처 : https://life-with-coding.tistory.com/485