Seeing as I don't know of a 'duplicate' question to flag, I'll put it in an answer.
A constructor looks (in some ways) like a method, but it isn't entirely the same. One of the (main) differences, is that it doesn't have a return statement, nor does it have a return type.
What it does, is create an instance of a class, and, if you assign that to a variable, as you did in your code, assigns it to said variable.
In a method, you could do something like this:
Nodo newNodo = getNodo(element);
while the getNodo method could do this:
public Nodo getNodo(T element) {
if ( someValidationFailed(element)) {
return null;
}
return new Nodo();
}
In this code, the null-check you wrote would make sense, because it is possible for this method to actually return null.
A constructor, however, can't.
Nodo newNodo = new Nodo(element);
if (newNodo == null) { //Dead code ¿why?
System.out.println("Overflow");
}
A constructor call can never result in null. It either results in the newNodo variable pointing to the new Nodo instance, or an Exception has been thrown.
If no Exception is thrown, the line after the Node newNodo = new Nodo(element);
can not possibly evaluate to true, since newNodo can not be null.
If, however, an Exception is thrown, that line will never be reached. Either the Exception is propagated further up the chain, or it is caught in a catch block, but it 'll never reach the:
if ( newNodo == null ){
line.
EDIT: a small clarification, after Andy Turner's comment.
Constructors are used to create Objects based on the class blueprint. By using the new keyword, you creates space for the new Object in the memory, and its fields are initialized.
Constructors
When you create an Object, using the new keyword, three steps are taken:
- Declaration
Nodo newNodo = new Nodo(element);
- Instantiation
Nodo newNodo = new Nodo(element);
- Initialization
Nodo newNodo = new Nodo(element);
So,indeed, it's not the constructor that creates the instance, it's the "entire process of running the constructor using the new keyword" that does.
Steps