Why does Java print null before "Hello"? Java OOP Programming Tips

☕ Why does Java print null before “Hello”? Here’s a simple example that surprises many developers: class X { int number = 10; X() { number = 100; show(); } public void show() { System.out.println("Show of X : " + number); } } class Y extends X { String message = "hello"; Y() { super(); message = "hello"; } public void show() { System.out.println("Show of Y : " + message); } } public class Main { public static void main(String[] args) { new Y(); } } 🧾 Output: Show of Y : null 💡 Explanation: When new Y() is created, Java first runs the parent constructor X(). Inside it, the show() method is called — but since Y overrides show(), the subclass version executes before Y is fully initialized. At that moment, message is still null. ✅ Key takeaway: Avoid calling overridable methods inside constructors. During superclass construction, subclass fields aren’t initialized yet — leading to results like null appearing before “Hello”. #Java #OOP #ProgrammingTips #CleanCode #Developers #Polymorphism

  • No alternative text description for this image

Consistency over perfection — and you’re proving it daily. Keep shining! 💪 Geeth Kalhara ♾️

See more comments

To view or add a comment, sign in

Explore content categories