So I came across some confusing code like this.
public class Class1 {
private Class2 class2 = new Class2(this);
public void dispose() {
if (class2 != null) {
class2.dispose();
}
if (class2 != null) {
class2.dispose();
class2 = null;
}
}
}
public class Class2 {
private Class1 class1;
private Class3 class3 = new Class3();
public Class2(Class1 class1) {
this.class1 = class1;
}
public void dispose() {
if (class3 != null) {
class3 = null;
}
class1 = null;
}
}
This is just an extract of what is important to this question from the actual classes. I know the way this code is written is not correct but it is like this.
Instance of Class1 is passed on to the constructor of Class2 & kept as a class variable, while the instance of Class1 keeps the instance of Class2 as a class variable.
When dispose() method is called in Class1, it calls the dispose method in Class2, and in the dispose method of Class2 it assigns null to the Class1 variable it has kept there.
This code does not produce an error and executes all the lines in the dispose() method of Class1.
Aren't the instance of Class1 that is being nullified by the dispose method in Class2, and the instance of Class1 calling the dispose() on Class2, the same?