Question

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?

Was it helpful?

Solution

Super() with no arguments inside mean there are more than one arguments to be defined?

No, super() just calls the no-arg constructor of the base class, in your case Object.

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 instance super("hello").

this.lastName = lastName; //when is this used?, when more than one args to be entered?

this.lastName = lastName; has nothing to do with super(). It merely states that the value of the constructor argument lastName should be assigned to the member variable lastName. This is equivalent to

public Contact(String contactId, String firstName, String lastNameArg,
               String email, String phoneNumber) {
    // ...
    lastName = lastNameArg;
    // ...

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top