What is the function of the super in a Java constructor?

Asked

Viewed 13,989 times

12

I have a daughter class that inherits from another abstract class, and in the class builder I have the following:

Public aluno(String nome, int idade){
    super(nome,idade);
}

What is the function of the "super" in the class constructor?

  • 2

    He calls the builder of the class you are inheriting.

2 answers

15


It’s to call the mother-class builder. If this class is composed at least in part by another inherited class, this part also needs to be initialized and this is a way to initialize the mother class data.

Let’s think that class would be:

class Aluno extends Pessoa

Then the super is calling a class builder Pessoa who has the appropriate signature to receive the name and age of the person who was obtained through the manufacturer of Aluno.

-4

When we have objects and make one class inherit the characteristics of another, using "extends", it is necessary to create constructors, but many of them because of of elegance define themselves with the same name of the parent class or superclass, so that we can differentiate to what we refer, we use "this" for the subclass and "super" for the superclass.

  • 6

    Either you don’t understand the question or you don’t know how it works.

  • 3

    It is not necessary to create constructors, we create only if we want/need. In Java, it is not a matter of elegance, it is a requirement of language syntax that the constructor uses the same class name (from own class, not the superclass). And its last sentence applies more to fields/methods than to constructors (we actually use this to refer to members of the class itself, and super for members of the superclass - including superscript methods). To explicitly invoke a specific superclass constructor (instead of implicitly the default constructor) it is required to super.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.