I do not understand why I give new
already in the attribute.
You are not required to "give new
" in the attribute declaration.
The galley does this to avoid that there is an instance with a null attribute.
For example:
public class Y {
public void fazAlgumaCoisa() {
//implementação
}
}
public class X {
private Y nova;
public Y getNova() {
return nova;
}
}
public class Z {
public void chamaMetodoDeY() {
X meuX = new X();
Y novaDeX = meuX.getNova();
novaDeX.fazAlgumaCoisa(); //Uma NullPointerException é lançada nessa linha
}
}
The "default value" for instance variables / non-primitive type attributes is null
.
Practices to avoid this scenario
To avoid scenarios like these, solutions like:
Practice # 1 : Instantiate / initialize the attributes in the statement itself (your example);
Practice # 2 : Get an instance (or value) by the constructor of your class:
public class Y {
public void fazAlgumaCoisa() {
//implementação
}
}
public class X {
private Y nova;
public X(Y nova) {
this.nova = nova;
}
public Y getNova() {
return nova;
}
}
public class Z {
public void chamaMetodoDeY() {
X meuX = new X();
Y novaDeX = meuX.getNova();
novaDeX.fazAlgumaCoisa(); //Nenhuma Exception será lançada nessa linha
//pois você receberá uma instância de Y pelo construtor
}
}
Practice # 3 : Dependency Injection:
This is already a slightly more advanced topic.
Dependency Injection essentially means that something or someone is going to "inject" a dependency (instance) into their attributes in an automagic way.
Usually we have a Dependency Injection Container that is responsible for injecting them.
A famous example is using the framework Spring :
public class Y {
public void fazAlgumaCoisa() {
//implementação
}
}
public class X {
@Autowired //Anotação do Spring que injeta uma instância de Y quando for necessário
private Y nova;
public Y getNova() {
return nova;
}
}
public class Z {
public void chamaMetodoDeY() {
X meuX = new X();
Y novaDeX = meuX.getNova();
novaDeX.fazAlgumaCoisa(); //Nenhuma Exception será lançada nessa linha
//pois o Spring injetará a instância necessária quando for necessário
}
}
Note: For this to work a few (a handful) of previous settings are needed.
Is it to call which constructor? (% with%)
The private Y nova = new Y();
constructor is called.