Hello. I have such a question: let's say I have an Achild class bin defined in my config. There is also the class Aparent - parent Achild. The question is - is the Aparent constructor always invoked when creating an Achild bean? And why does Spring do it at all? thank
1 answer
Spring has nothing to do with it, this is a fundamental position in Java: each constructor of each class (except java.lang.Object
) is always called first by the constructor of its ancestor, and that of its own, and so on.
UPD No, this applies to all designers. The compiler itself substitutes the call to the parent constructor if you do not do this manually:
class A { public A() { // super(); - этот вызов компилятор вставит автоматически System.out.println("It's A"); } } class B extends A { public B() { // super(); - и этот тоже System.out.println("It's B"); } }
Call new B();
will lead to the conclusion
It's A It's B
You can also insert a super()
call yourself, including a call to any other parent constructor, not just without parameters. There is another nuance when you get a compilation error, if the compiler inserts a call to super()
for you, and there is no such constructor in the parent class ( @Nikolay Artamonov would answer you in detail and with examples, you need to write a lot to fully reveal the topic). In general, it is worth reading about it, since using Spring without an understanding of the fundamental concepts of Java is unwise.
- I meant that at the parent class only the default constructor can be automatically called. - Vladimir
- well, almost yes - a constructor with no parameters is invoked - by default or personally written. - yozh
- Another such question is (there is another nuance when you get a compilation error, if the compiler inserts a call to super () for you, and there is no such constructor in the parent class) - but isn't the default constructor automatically generated? Is it really necessary to define it even just empty? - Vladimir
- if there are no empty fields waiting to be defined, then the constructor is optional - Zowie