Bird
0
0

Consider this code:

hard📝 Application Q9 of 15
Java - Static Keyword
Consider this code:
class A {
  static int x = 5;
}
class B extends A {
  static int x = 10;
}
public class Test {
  public static void main(String[] args) {
    System.out.println(A.x);
    System.out.println(B.x);
  }
}

What will be the output?
ACompilation error due to static variable hiding
B10 and 10
C5 and 5
D5 and 10
Step-by-Step Solution
Solution:
  1. Step 1: Understand static variable hiding in inheritance

    Class B declares its own static variable x, hiding A's x.
  2. Step 2: Check output of each class's static variable

    A.x is 5, B.x is 10, so printing them outputs 5 and 10 respectively.
  3. Final Answer:

    5 and 10 -> Option D
  4. Quick Check:

    Static variable hiding outputs distinct values = D [OK]
Quick Trick: Static variables in subclass hide superclass variables [OK]
Common Mistakes:
  • Assuming subclass static variable overrides superclass's
  • Expecting compilation error due to hiding
  • Thinking both print same value

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes