Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q5 of 15
Java - Constructors
What will be the output of this code?
class A {
  int num = 100;
  void print() {
    System.out.println(this.num);
  }
}
class B extends A {
  int num = 200;
  void print() {
    System.out.println(num);
    System.out.println(this.num);
    System.out.println(super.num);
  }
}
public class Test {
  public static void main(String[] args) {
    B obj = new B();
    obj.print();
  }
}
A200 100 200
B100 200 100
C200 200 100
D100 100 200
Step-by-Step Solution
Solution:
  1. Step 1: Understand variable hiding in subclass

    Class B has its own num variable hiding superclass's num.
  2. Step 2: Analyze print statements

    num and this.num in B refer to B's num (200). super.num refers to A's num (100).
  3. Final Answer:

    200 200 100 -> Option C
  4. Quick Check:

    this.num = subclass variable [OK]
Quick Trick: Use super to access superclass variables [OK]
Common Mistakes:
  • Confusing this.num with super.num
  • Assuming num always refers to superclass
  • Ignoring variable hiding in subclass

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes