Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - use of super() in the given example

Tags:

java

super

I've just started to learn the Spring framework and I found some tutorial at javatpoint.com.

I've got this code (nothing special, only prints some questions and answers):

private int id;
private String name;
private Map<Answer,User> answers;

public Question(){}
public Question(int id, String name, Map<Answer,User> answers){
    super();
    this.id = id;
    this.name = name;
    this.answers = answers;
}

My question is : Why is he using that empty constructor and the keyword super() ? The app works without them and I don't get what are they good for in this code.

P.S. : There is no super class or something like that.

like image 250
Valentin Emil Cudelcu Avatar asked Jun 13 '16 06:06

Valentin Emil Cudelcu


2 Answers

A no-arg constructor (e.g., Question()) can be useful in several cases - if you're using a class as a bean and wish to lazily initialize its members, serializing it over GWT, etc.. Without any context provided in the example, this is indeed redundant.

The call to super() is completely redundant, and would be performed implicitly if no [other] call to super is specified.

like image 108
Mureinik Avatar answered Oct 21 '22 11:10

Mureinik


Empty constructor is not needed in most cases, only when you use your class in some poor framework like Hibernate or JPA, where you need empty constructor for the framework to create your class. Then the empty constructor is for the framework and non-empty one is usually for tests or other usages.

In the example above I don't see any evidence that you use such framework so this empty constructor is not needed.

As for the super() it is NOT needed at all.

like image 24
Krzysztof Krasoń Avatar answered Oct 21 '22 09:10

Krzysztof Krasoń