If you create an instance of a class, then the variable is a reference to the object in memory.
If you delete (here I will see, set `null* to a reference, that object can no longer be accessed in memory, and the space it occupies will be available to be overwritten, but if you delete only the reference to it in another object, it continues to exist.
So, about your question "despite that knot that I exclude can no longer be accessed, it continues to exist?" existing is a relative concept. A chained list with object references, for example:
Lista > obj1 > obj2 > obj3 ...
Delete obj3 reference in obj2 in the list (for example obj3.setNo(null)
) , it ceases to exist for the list, but obj3 still exists in memory.
See this simple example of a list that demonstrates that, an object "ceases to exist" for the program:
class Main {
public static void main(String[] args) {
var lista = new Classe();
var no1 = new Classe();
var no2 = new Classe();
no1.setNo(no2);
lista.setNo(no1);
System.out.println("Lista com todos os nos");
System.out.println(lista.getNo()); // retorna a instancia de no1
System.out.println(lista.getNo().getNo());// retorna a instancia no2
no1.setNo(null); // seto null, removendo a referencia ao no2 que existia no no1
System.out.println("Lista sem o no2");
System.out.println(lista.getNo()); // retorna a instancia no1
System.out.println(lista.getNo().getNo()); // retorna null, a referencia a no2 foi quebrada
System.out.println(no2); // o objeto no2 ainda existe
}
}
class Classe {
private Classe no;
public Classe getNo() {
return no;
}
public void setNo(Classe no) {
this.no = no;
}
}
And the output is:
Lista com todos os nos
Classe@1175e2db
Classe@36aa7bc2
Lista sem o no2
Classe@1175e2db
null
Classe@36aa7bc2
You can see it working here: https://www.mycompiler.io/
I didn’t quite understand your question, but if your doubt is about exchanging the reference of an object for another in a variable, the object that lost the reference will be erased from memory by the Garbage Collector.
– JeanExtreme002
See if it helps: What is Garbage Collector and how it works?
– Augusto Vasques