When I write a constructor in my java class, I typically do not invoke super() in there. When I generate the constructor from eclipse source code editor, why does it always add the super() in there?
Am I wrong for not adding this by default in the constructors I write? Any thing wrong with leaving the super() call in the constructor if I decide to use eclipse code generator?
super() acts as immediate parent class constructor and should be first line in child class constructor. this() acts as current class constructor and can be used in parametrized constructors. When invoking a superclass version of an overridden method the super keyword is used.
Note: 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.
However, using super() is not compulsory. Even if super() is not used in the subclass constructor, the compiler implicitly calls the default constructor of the superclass.
“super” and “this” in Java are two predefined keywords, that cannot be used as an identifier. “super” in Java is used to refer to methods, static and instance variables, constructors of an immediate parent class. “this” in Java is used to refer to methods, static and instance variables, constructors of a current class.
Nothing wrong it's just a coding style preference. Some people like to write code that is implicit and some don't.
If you don't call super constructor from your child class constructor compiler will place call to super's default constructor in byte code for you. See this SO question as well
As @Kon correctly points out, there is an implicit call to the default super constructor anyway (this can be easily verified by checking the bytecode with javap -c
). If you don't want Eclipse to make it explicit, simply check the "Omit call to default constructor super()" checkbox at the bottom of the constructor creation GUI.
Am I wrong for not adding this by default in the constructors I write?
No, as long as long as you're referring to the default super constructor call super()
. If the super constructor takes parameters, for example, then you need to make the call explicit.
Any thing wrong with leaving the super() call in the constructor if I decide to use eclipse code generator?
No, not at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With