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();
    }
}

  1. A.

    Animal makes a sound

  2. B.

    Dog barks

  3. C.

    Compilation error

  4. 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".

Explore the full course: Tpsc Assistant Technical Officer