+ 3

[SOLVED] Java extends problem

Hello, PROgrammers! Check this code, can anyone explain why the method sayHello() is printing there? I'm just calling my "exit" class, but java is calling the "welcome" class first then calling "exit" class... I'm not sure why that's is happening... https://code.sololearn.com/cHGV2NlcJ2ed/?ref=app

2nd May 2020, 6:28 PM
KingDaniel2004
KingDaniel2004 - avatar
4 Antworten
+ 2
This is exactly what should be happening. Your exit class extends the welcome class. In your welcome class' constructor you call the sayHello() method. Since welcome is a parent class of exit its constructor is called first. The parent must exist in order for the child to exist. You can think of super/ parent classes as wrapping around their sub/child classes. The super most objects constructor is called, followed by the next super most object etc towards the child class. Then when destroyed their destructors are called in opposite fashion from child outward toward parent.
2nd May 2020, 6:37 PM
ChaoticDawg
ChaoticDawg - avatar
+ 3
ChaoticDawg oh... So Parent => child If u not calling the parent, it will automatically called before calling the child... Thanks much for clarification 😁👍
2nd May 2020, 6:42 PM
KingDaniel2004
KingDaniel2004 - avatar
+ 3
Avinesh thanks for clarification! 😁
2nd May 2020, 6:43 PM
KingDaniel2004
KingDaniel2004 - avatar
+ 2
It's not a problem btw. Always the parent class constructor is called first whenever you try to create an instance of the child class generally to initialize all the members that are being inherited by the child class.
2nd May 2020, 6:37 PM
Avinesh
Avinesh - avatar