📢 Too many exams? Don’t know which one suits you best? Book Your Free Expert 👉 call Now!


    Question

    Consider the following code snippet (Java-like):

        class Animal {         public void makeSound() {             System.out.println("Animal makes a sound");         }     }     class Dog extends Animal {         @Override         public void makeSound() {             System.out.println("Dog barks");         }     }     public class Test {         public static void main(String[] args) {             Animal myAnimal = new Dog();             myAnimal.makeSound();         }     }     What will be the output of this code?
    A Animal makes a sound Correct Answer Incorrect Answer
    B Dog barks Correct Answer Incorrect Answer
    C Compilation Error Correct Answer Incorrect Answer
    D Runtime Error Correct Answer Incorrect Answer
    E Nothing, the program will not execute. Correct Answer Incorrect Answer

    Solution

    This demonstrates runtime polymorphism (method overriding). Even though myAnimal is declared as type Animal, it actually refers to a Dog object. When makeSound() is called, the JVM (Java Virtual Machine) determines the actual type of the object at runtime and invokes the makeSound() method defined in the Dog class.

    Practice Next
    ask-question