Please explain
public class Contact {
private String contactId;
private String firstName;
private String lastName;
private String email;
private String phoneNumber;
public Contact(String contactId,String firstName, String lastName, String email, String phoneNumber) {
super(); //what does standalone super() define? With no args here?
this.firstName = firstName;
this.lastName = lastName; //when is this used?, when more than one args to be entered?
this.email = email;
this.phoneNumber = phoneNumber;
}
Super() with no arguments inside mean there are more than one arguments to be defined? And is this done with the help of "this.xxx" ?
Why dint we define in the "public class Contact" itself. Why we defined again and called its arguments here?
super()
calls the default (no-arg) constructor of the superclass. This is because in order to construct an object, you have to go through all the constructors up the hierarchy.super()
can be omitted - the compiler automatically inserts it there.In your case, the superclass is
Object
No,
super()
just calls the no-arg constructor of the base class, in your caseObject
.It does nothing really. It just makes it explicit in the code, that you're constructing the base class using the no-arg constructor. In fact, if you left
super()
out, it would be added back implicitly by the compiler.So what is the
super()
for if it's added implicitly anyway? Well, in some cases, a class does not have a no-arg constructor. Subclasses of this class must explicitly call some super-constructor, using for instancesuper("hello")
.this.lastName = lastName;
has nothing to do withsuper()
. It merely states that the value of the constructor argumentlastName
should be assigned to the member variablelastName
. This is equivalent to