The following code (shortened version of the class) I have seen in a Java Video-Tutorial.
public class Address {
private String firstName;
private String lastName;
public Address() {
super();
}
public Address(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
...
}
The class which is shown there has no extend
keyword. Nevertheless super()
is used within the constructor without a parameter.
It calls the constructor of Object class? Am I right?
But why?
What is the reason for having this call of super()
?
Constructors of superclasses are invoked when you create an instance of your class. In case your class extends sth explicitly, there are two options:
Calling super() without parameters basically means that you invoke a default constructor. It's not necessary, because it will be invoked even if you don't do it explicitly.
Since all the objects in java implicitly extend Object, then the default constructor of Object is invoked all the time you create an instance of the class. super() just makes it explicit. But, why should we add explicitness to something that is quite clear already.
Moreover, that's sometimes added by IDE when you use code generation tools(e.g. Eclipse).
You can read really good description on how consturtors of class/superclass work in a book for OCA preparation: https://www.amazon.com/OCA-Certified-Associate-Programmer-1Z0-808/dp/1118957407
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