Empty constructor without calling super()

Asked

Viewed 733 times

6

When I do parameterized constructors, I create an empty constructor as well.

In the empty constructor, should I always make the call to super()? Why? (Take into account, that my class is just a Javabean.)

  • Related: http://answall.com/q/45028/101

  • @bigown That part I understand (when there are sub-classes and superclasses). My doubt is regarding a Javabean that does not inherit from another class. Which by default inherits from Objects. Thank you.

  • I edited my answer because I got it right, but when I went to justify it it was by an intuitive way but that does not reflect the reality of Java. The answer was correct, but by crooked lines. Seeing the reply of the utluiz I realized this.

2 answers

6

In Java, every class necessarily needs to call a constructor from its superclass, this being the first command within the constructor.

Even if one class does not extend any other class directly, then the super() of Object will be called anyway.

What confuses a little who has not yet studied this concept is that when you do not explicitly call the super() in a constructor, the Java compiler implicitly adds a call to the parameter-free superclass constructor.

This occurs in the same way that the compiler also adds a default constructor, with no parameters, when you do not explicitly declare any constructor.

If the superclass does not have a constructor without parameters, then the compiler forces you to call one of the constructors using the super.

4


It is always necessary to initialize the instance with the construction of the object integrally, that is, the part of the upper class needs to be built, and so has to call the super(). If this is not done explicitly in the constructor the compiler does it for you, even for the Objects. You only need to do it manually if you have a reason, one of them is when the mother class does not have a default constructor.

Specifically this point regardless of whether it is Beans or not, Beans has other requirements.

  • One of the Javabean conventions is to use an empty constructor. So I used it for exemplification. Likewise, remove my doubt. "Objects does not need construction." Thanks!

  • Yes, I know, it’s a requirement of his own. And from what you’re asking, I think you understand that only in some cases do you need to create the constructor without parameters. It can be created automatically if it does not create other constructs.

  • I usually use super() only when the parent class needs to receive a parameter, differentiated or not. This happens a lot in AS3 when creating classes that inherit from Event. The rest, I don’t even care about putting super().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.