Java · Question 29 · Hard

What will be the output of the following Java program?

class A {
    int x = 10;
}

class B extends A {
    int x = 20;
}

public class Main {
    public static void main(String[] args) {
        A obj = new B();
        System.out.println(obj.x);
    }
}
  1. 20
  2. 30
  3. Compilation error
  4. 10
Answer and explanation

Answer: D. 10

Explanation: Fields are not overridden; B's x only hides A's x. Field access uses the reference type, which is A, so obj.x is 10. Only methods are chosen by the object's runtime type.

Previous: What will be the output of the following Java program? · Next: What will be the output of the following Java program?

Practise java

Try a fresh set of java questions with an explanation after every answer, free and without signing up: Java practice. Or sit a full placement mock test.

More java questions

More technical & programming practice

Python · Data Structures · Algorithms · Object-Oriented Programming · DBMS · SQL · Operating Systems · Computer Networks

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge