Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

super() in a constructor of a class without inheritance [duplicate]

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()?

like image 559
cluster1 Avatar asked Mar 09 '23 22:03

cluster1


1 Answers

Constructors of superclasses are invoked when you create an instance of your class. In case your class extends sth explicitly, there are two options:

  • If the super class has a default constructor, then it's invoked;
  • In case there is no default constructor, you should specify which constructor you invoke and send corresponding arguments for it.

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

like image 145
dvelopp Avatar answered Apr 26 '23 14:04

dvelopp