Bird
0
0

What will be the output of this code snippet?

medium📝 Predict Output Q5 of 15
Java - Inheritance

What will be the output of this code snippet?

class Parent {
    int x = 10;
}
class Child extends Parent {
    int x = 20;
    void printX() {
        System.out.println(super.x);
    }
}
public class Test {
    public static void main(String[] args) {
        Child c = new Child();
        c.printX();
    }
}
A10
B20
CCompilation error
DRuntime error
Step-by-Step Solution
Solution:
  1. Step 1: Understand variable hiding and 'super' keyword

    The child class has its own x variable hiding the parent's x. Using super.x accesses the parent's x.
  2. Step 2: Identify printed value

    The print statement prints parent's x value, which is 10.
  3. Final Answer:

    10 -> Option A
  4. Quick Check:

    super.x accesses parent variable = 10 [OK]
Quick Trick: 'super' accesses parent class members hidden by child [OK]
Common Mistakes:
  • Printing child's x instead of parent's
  • Confusing method overriding with variable hiding
  • Expecting errors due to variable hiding

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes