JavaAdvanced#puzzle#oop#polymorphism

What does this output? class Base { int x = 10; int getX() { return x; } } class Derived extends Base { int x = 20; int getX() { return x; } } Base obj = new Derived(); System.out.println(obj.x); System.out.println(obj.getX());

Fields are resolved statically based on the declared reference type (no polymorphism for fields), so obj.x accesses Base's x = 10. Methods are resolved dynamically based on the actual object type (polymorphism), so obj.getX() calls Derived's override, returning 20.

Example
Base obj = new Derived();
System.out.println(obj.x);      // 10 (field access is static)
System.out.println(obj.getX()); // 20 (method call is dynamic/polymorphic)

Related Questions

1
JavaAdvanced#jvm

What is the difference between a class loader's parent delegation model levels: Bootstrap, Extension/Platform, and Application?

Open
2
JavaAdvanced#jvm

What is JIT compilation?

Open
3
JavaIntermediate#oop#fundamentals

What is the difference between shallow copy and deep copy in Java?

Open