+ 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
4 ответов
+ 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.
+ 3
ChaoticDawg oh... So
Parent => child
If u not calling the parent, it will automatically called before calling the child...
Thanks much for clarification 😁👍
+ 3
Avinesh thanks for clarification! 😁
+ 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.