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();
}
}
Tripura Public Service Commission - 2025,
Answer: B
The output is Dog barks.
The reference obj has the type Animal but points to a Dog object created with new Dog(). Dog overrides makeSound(), and Java chooses an overridden instance method by the object's actual class at run time (dynamic dispatch), so obj.makeSound() runs the Dog version and prints Dog barks.
'Animal makes a sound' would be right only if Java used the reference type, which is the rule for static or private methods and for fields, not for overridden instance methods. There is no compilation error: Dog is a subclass, so assigning it to an Animal reference is legal, and the call is valid because Animal declares makeSound(). There is no runtime error either, since the object is not null and the method exists.
Please log in or register to report this question.