ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
class Animal {
    String sound() { return "..."; }
}
class Dog extends Animal {
    @Override
    String sound() { return "Woof"; }
}
class Puppy extends Dog {
}
public class Main {
    public static void main(String[] args) {
        Animal a = new Puppy();
        System.out.println(a.sound() + " " + (a instanceof Dog) + " " + (a.getClass() == Dog.class));
    }
}
  1. A. Woof true true
  2. B. Woof true false
  3. C. ... true false
  4. D. Woof false false

Correct answer: B. Woof true false

Puppy inherits Dog's override unchanged, so a.sound() dispatches dynamically to Dog.sound(), returning Woof. instanceof checks the whole hierarchy, so a instanceof Dog is true (a Puppy is-a Dog). getClass() returns the exact runtime class, Puppy.class, which is not == to Dog.class, so that comparison is false.

More OOP with C++ and Java questions

Exams that ask this topic