Java · Question 7 · Medium

What will be the output of the following Java program?

class Animal {
    String sound() { return "..."; }
}

class Dog extends Animal {
    String sound() { return "Woof"; }
}

public class Main {
    public static void main(String[] args) {
        Animal a = new Dog();
        System.out.println(a.sound());
    }
}
  1. ...
  2. Compilation error
  3. Woof
  4. Woof...
Answer and explanation

Answer: C. Woof

Explanation: sound() is an overridden instance method, so the call is resolved at run time by the actual object type (Dog), not by the reference type (Animal).

Previous: What will be the output of the following Java program? · Next: What will be the output of the following Java program?

Practise java

Try a fresh set of java questions with an explanation after every answer, free and without signing up: Java practice. Or sit a full placement mock test.

More java questions

More technical & programming practice

Python · Data Structures · Algorithms · Object-Oriented Programming · DBMS · SQL · Operating Systems · Computer Networks

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