문제
다음 Java 프로그램의 실행 결과는?
Javaclass Animal { void sound() { System.out.print("Animal"); } } class Dog extends Animal { void sound() { System.out.print("Woof"); } } public class Test { public static void main(String[] args) { Animal a = new Dog(); a.sound(); } }
① Animal ② Woof ③ Animal Woof ④ 컴파일 오류
정답
2번
해설
Animal 타입으로 선언되었지만 실제 객체는 Dog이므로, 런타임에 Dog 클래스의 오버라이딩된 sound() 메서드가 호출된다. 이는 Java의 다형성(polymorphism) 개념이다.