Why should the parent class constructor (in relation to inheritance and constructor) be performed first! I wonder if my guess is correct.

Asked 2 years ago, Updated 2 years ago, 112 views

Ian Media is a student who is studying with a book called 'The first java programming'.

I was studying inheritance and constructor, but the book said that in order for an explicit constructor or implied constructor of a lower class to be executed, an implicit constructor of a higher class must be performed first, and an error occurs if there is no implied constructor.

So I understand that even if there are explicit constructors in the upper class, if you don't write super() statements to allow the implicit constructors to run, then I see in the example that if you run only the explicit constructors in the upper class, you don't get an error.

From now on, I'm curious. I studied again through googling and understood Any constructor of the higher class must be performed first -> That is, any constructor in the upper class needs to be performed before the constructor in the lower class --> why) Isn't it because the constructor in the upper class needs to be performed first so that the upper class can rise to memory and the lower class can inherit the member variable, method of the upper class?

I wonder if my understanding is logically correct.

java inheritance constructor

2022-09-22 17:57

1 Answers

[Voiceover] Right. It is explained in the official Java tutorial and specification.

If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.

It doesn't matter if there is an explicit constructor, and if not, the compiler automatically calls a constructor without parameters. Of course, if there are no parameters, an error will occur.

The specification explains that the parent class must be initialized as shown below.

Before a class is initialized, its direct superclass must be initialized

Therefore, I think you can say that what you understand is correct.


2022-09-22 17:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.