Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

다중 레벨 상속이 있는 Java 런타임 다형성


메서드 재정의는 런타임 다형성의 예입니다. 메서드 재정의에서 하위 클래스는 상위 클래스의 서명과 동일한 서명을 가진 메서드를 재정의합니다. 컴파일 시간 동안 참조 유형에 대한 검사가 수행됩니다. 그러나 런타임에서 JVM은 개체 유형을 파악하고 해당 특정 개체에 속한 메서드를 실행합니다.

다단계 상속의 모든 수준에서 메서드를 재정의할 수 있습니다. 개념을 이해하려면 아래 예를 참조하십시오 -

class Animal {
   public void move() {
      System.out.println("Animals can move");
   }
}
class Dog extends Animal {
   public void move() {
      System.out.println("Dogs can walk and run");
   }
}
class Puppy extends Dog {
   public void move() {
      System.out.println("Puppy can move.");
   }
}
public class Tester {
   public static void main(String args[]) {
      Animal a = new Animal(); // Animal reference and object
      Animal b = new Puppy(); // Animal reference but Puppy object
      a.move(); // runs the method in Animal class
      b.move(); // runs the method in Puppy class
   }
}

출력

Animals can move
Puppy can move.