I don’t understand why I give new
already in the attribute.
You are not obliged to "give new
" in the declaration of the attribute.
People do this to prevent 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/attributes of primitive types is null
.
Practices to avoid this scenario
To avoid scenarios like these, solutions such as:
Practice #1: Instantiate/initialize attributes in the declaration itself (your example);
Practice #2: Receive an instance (or value) by the constructor of its 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.
Injection of Dependencies basically means that something or someone will "inject" a dependency (instance) into its shape attributes self-driving.
Usually we have a Dependency Injection Container who 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 are necessary some (a handful) of previous settings.
Serves to call which builder? (private Y nova = new Y();
)
The builder of Y
is called.
And why wouldn’t it? It’s equal C++. You really wanted to put one class inside the other?
– Maniero
What it is doing seems to be composition, when an object is composed of another object. In this case, the internal object is created within the external. What would be the equivalent code in C++?
– Woss
By the way, why define classes within a class?
– Woss
In Java, you only have references to objects, so you need to give a new
– Jefferson Quesado