Bird
0
0

What will be the output of the following code?

medium📝 Predict Output Q13 of 15
Java - Abstraction
What will be the output of the following code?
abstract class Animal {
    abstract void sound();
    void sleep() {
        System.out.println("Sleeping");
    }
}

class Dog extends Animal {
    void sound() {
        System.out.println("Bark");
    }
}

public class Test {
    public static void main(String[] args) {
        Animal a = new Dog();
        a.sound();
        a.sleep();
    }
}
ASleeping\nBark
BCompilation error
CBark\nSleeping
DRuntime error
Step-by-Step Solution
Solution:
  1. Step 1: Understand method calls on abstract class reference

    The variable a is of type Animal but refers to a Dog object. Calling sound() calls Dog's implementation, printing "Bark".
  2. Step 2: Call the concrete method from abstract class

    Calling sleep() uses the method defined in Animal, printing "Sleeping".
  3. Final Answer:

    Bark Sleeping -> Option C
  4. Quick Check:

    Dog sound then Animal sleep = Bark then Sleeping [OK]
Quick Trick: Abstract ref calls subclass method, regular method runs as is [OK]
Common Mistakes:
  • Expecting compilation error for abstract class reference
  • Confusing method call order
  • Thinking abstract class methods can't be called

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes