Bird
0
0

Given these classes:

hard📝 Application Q15 of 15
Java - Inheritance
Given these classes:
class Animal {
  String name;
  Animal(String name) {
    this.name = name;
  }
  void sound() {
    System.out.println("Animal sound");
  }
}
class Dog extends Animal {
  Dog() {
    super("Dog");
  }
  void sound() {
    super.sound();
    System.out.println("Bark");
  }
}
public class Test {
  public static void main(String[] args) {
    Dog d = new Dog();
    d.sound();
    System.out.println(d.name);
  }
}

What is the output when running Test.main()?
AAnimal sound Bark Dog
BBark Animal sound Dog
CAnimal sound Dog Bark
DCompilation error due to super()
Step-by-Step Solution
Solution:
  1. Step 1: Understand constructor chaining

    The Dog constructor calls super("Dog"), setting name to "Dog" in Animal.
  2. Step 2: Trace the sound() method call

    Dog.sound() calls super.sound() which prints "Animal sound", then prints "Bark".
  3. Step 3: Print the name field

    Printing d.name outputs "Dog".
  4. Final Answer:

    Animal sound Bark Dog -> Option A
  5. Quick Check:

    super() sets name, super.sound() prints parent sound = A [OK]
Quick Trick: super() sets parent state; super.method() calls parent method [OK]
Common Mistakes:
  • Expecting Dog before Animal sound
  • Confusing order of prints
  • Thinking super() causes error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes