Super () in class constructor without inheritance

The following code (shorthand version of the class) that I saw in the 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 shown there does not have a keyword extend

. However, it is super()

used inside a parameterless constructor.

Does it call the constructor of the Object class? I'm right?

But why?

What is the reason for this challenge super()

?

+3


source to share


2 answers


Superclass constructors are called when your class is instantiated. If your class extends sth explicitly, there are two options:

  • If the superclass has a default constructor, it calls:
  • If there is no default constructor, you must specify which constructor you are calling and send the appropriate arguments to it.

Calling super () with no parameters basically means you are calling the default constructor. This is not necessary, because it will be called even if you do not explicitly do so.



Since all objects in java implicitly extend Object, then the default Object constructor is called all the time you instantiate the class. super () just makes it explicit. But why should we add evidence to what is already quite clear.

Also, this is sometimes added by the IDE when using code generation tools (like Eclipse).

You can read a really good description of how class / superclass developers work in the book for preparing OCA: https://www.amazon.com/OSA-Certified-Associate-programmer-1Z0-808/dp/1118957407

+3


source


this is what you get when you let your IDE generate constructors for your class .. since this class does not extend anything and calling super is the same as calling the constructor of the object's class, which actually takes no effect on the class implementation Address

so in your case

public Address() {
    super();
}

      



coincides with

public Address() {

}

      

+3


source







All Articles