What is the output of the following Java code ? Java Copy code class Animal {…
2025
What is the output of the following Java code ?
Java
Copy code
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("Dog barks");
}
}
public class Test {
public static void main(String[] args) {
Animal obj = new Dog();
obj.makeSound();
}
}- A.
Animal makes a sound
- B.
Dog barks
- C.
Compilation error
- D.
Runtime error
Attempted by 46 students.
Show answer & explanation
Correct answer: B
The code demonstrates runtime polymorphism in Java. The reference variable obj is of type Animal but holds a Dog instance. When makeSound() is called, the JVM invokes the overridden method in Dog class at runtime, printing "Dog barks".