JavaAdvanced#puzzle#oop

What happens when you compile and run this code? class Parent { static void greet() { System.out.println("Parent"); } } class Child extends Parent { static void greet() { System.out.println("Child"); } } Parent p = new Child(); p.greet();

Static methods are resolved at compile time based on the reference type, not the runtime object type — this is called method hiding, not overriding. Since p is declared as Parent, Parent.greet() is called, printing "Parent".

Example
Parent p = new Child();
p.greet(); // Output: "Parent" (static binding, based on reference type)

Related Questions

1
JavaIntermediate#puzzle#arrays

What is the output of this array comparison? int[] a = {1, 2, 3}; int[] b = {1, 2, 3}; System.out.println(a == b); System.out.println(a.equals(b)); System.out.println(Arrays.equals(a, b));

Open
2
JavaAdvanced#puzzle#oop

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());

Open
3
JavaAdvanced#jvm

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

Open