What is the super() function for;

Asked

Viewed 15,572 times

3

I am studying Java and I need to understand the logic of a code here. I wanted to know what this piece of code does:

public class UsuarioController extends HttpServlet {
    private DAO dao;    

    public UsuarioController() {
        super();
    }...

4 answers

8


The super() serves to call the superclass builder. It is always called, even when it is not explicit in the code, when it is explicit it must be the first item within the constructor.

See for example the code below:

public class Teste {
    public static void main(String[] args) {
        new Sub();
    }
}

class Super {
    public Super() {
        System.out.println("super");
    }
}

class Sub extends Super {
    public Sub() {
        System.out.println("sub");
    }
}

Exit:

super
sub

Although the Test class is instantiating an object of the Sub class, both Sub and Super constructors are called.

5

In Java super() invokes the constructor, without arguments, of the derived class (parent).

In your example, and since UsuarioController extend the class HttpServlet will invoke the constructor default class HttpServlet.

The directive super, without parentheses, it also allows invoking methods of the class that was derived through the following syntax.

super.metodo();

This is useful in cases where you do override (overrides) a parent class method and you want to invoke the method original.

2

When we work with inheritance to superclass is the class we inherited and the sub class is the class we inherit from the superclass.

The subclass can override superclass methods and of course implement its own methods. Each class has two references: the this, which refers to the instance of itself and the super which reference to superclass.

In practice it works like this:

public class Pessoa {
  private String nome;      

  public Pessoa() {
     // Construtor padrão. 
  }

  public Pessoa(String nome) {
     this.nome = nome; // Aqui fazemos referência a instância da classe
  }

  public void chorar() {
    System.out.print("Pessoa chorando");
  }

  public void greet() {
     System.out.print("Olá "+this.nome);
  }
}

public class Chaves extends Pessoa {
  public void chorar() {
    System.out.print("pi pi pi pi pi pi pi ");
    super.chorar(); // Aqui eu invoco o método da superclasse se eu quiser.
  }
}

Note that the person class has a method greet(), which is publicly accessible in any instance of Pessoa and their subclasses, only nomeonly accessible by the manufacturer of Pessoa, and now? Simple: Just change the constructor of Chaves, in this way:

public Chaves() {
  super("Chaves"); // Lembra que temos um construtor com argumentos em Pessoa?
}

I can call other superclass methods too:

public foo() {
  this.fazAlgumaCoisa();
  super.fazOutraCoisa(); 
  /* também é possível usar this.fazOutraCoisa(). Se eu não sobrescrever o           
     método fazOutraCoisa eu prefiro usar o super, deixando claro que este
     método está na superclasse. Faço assim para facilitar  aleitura*/
}

Some interesting things we should know about the superis as follows:

When declaring a class without the default constructor (No arguments) jvm creates one for you as follows:

public Classe() {
  super(); // Aqui o super chama o construtor da superclasse;
}

When we talk about builders, super() should always be the first method to be called:

public Classe() {
   this.fazAlgumaCoisa();
   super(); // erro de compilação
}


public Classe() {
   super(); // Ok
   this.fazAlgumaCoisa(); //OK
}

The use of the super is not mandatory and it is good practice to make the correct use of it to facilitate the reading of the code. Below are some recommendations:

  • We should call the builder of superclasseonly if it makes sense. Doing so makes it clear to other programmers: Hey, there’s important stuff going on in the superclass. Get smart!

  • Methods that are inherited and not superscripted should never be invoked using this.metodoHerdado(), prefer super.metodoHerdado(). This will make it clear to other programmers that this method is implemented in superclass and not in the class he’s working in. This is just a recommendation.

  • 2

    I’m no scholar of OOP, but I find the second recommendation a little strange. This would not be recommended only in cases where the subclass overrides the method, as stated in Reply from @Bruno?

  • @bfavaretto Not necessarily. Understand this: If I am using a super class method that has not been overloaded I can use both this and super, I will have the same result. However using the super makes it clear to other people that this method is in super class (imagine a very large class, it will not waste time looking). It’s just for reading, really, nothing more...

1

Serves to call the builder of the parent class of the class who is calling the super(); It can also be called with parameters if the parent class has a constructor with the proper parameter, such as super(parametro);

In your case will call the builder HttpServlet() parent-class.

To study well for the test, read the java manual: https://docs.oracle.com/javase/tutorial/java/IandI/super.html

Browser other questions tagged

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