Object-Oriented Programming · Question 6 · Medium

What is the output of the following Java code?

class Animal {
    void sound() { System.out.println("Generic"); }
}
class Dog extends Animal {
    void sound() { System.out.println("Bark"); }
}
// in main:
Animal a = new Dog();
a.sound();
  1. Bark
  2. Generic
  3. Compilation error
  4. Generic followed by Bark
Answer and explanation

Answer: A. Bark

Explanation: sound() is an overridden instance method, so the call is dispatched on the actual object type (Dog) at runtime, even though the reference type is Animal.

Previous: A Car object contains an Engine object. This "has-a" relationship is best… · Next: What is the output of the following Java code?

Practise object-oriented programming

Try a fresh set of object-oriented programming questions with an explanation after every answer, free and without signing up: Object-Oriented Programming practice. Or sit a full placement mock test.

More object-oriented programming questions

More technical & programming practice

DBMS · SQL · Operating Systems · Computer Networks · Software Engineering · Cloud & DevOps · GenAI Basics · Pseudo-code

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge