Question discussion

What is the output of the following Java program?class P { int x = 10; int get() { return x; } } class C extends P { int x = 20; int get()…

1331Medium DSSSB TGT Computer Science 0 replies

What is the output of the following Java program?

class P { int x = 10; int get() { return x; } }
class C extends P { int x = 20; int get() { return x; } }
public class Main {
    public static void main(String[] args) {
        P p = new C();
        System.out.println(p.x + " " + p.get() + " " + ((C) p).x);
    }
}
  • A20 20 20
  • B10 10 20
  • C10 20 20
  • D10 20 10
Correct answer: C

Explanation

Fields are not overridden — p.x uses the reference type P (10) — while the method get() is dispatched dynamically to C (20), and ((C) p).x reads C's field (20).

Discussion 0

Nobody has replied yet. Start the discussion!