I am having a difficult time understanding the way static classes are using in the following scenario.
Let’s say I declare a class as follows:
public class TestLibrary {
private static final TestLibrary library = new TestLibrary();
private ErrorHandler errorHandler = null;
public static TestLibrary getLibrary() {
return library;
}
public ErrorHandler getErrorHandler() {
return errorHandler;
}
public int run(String[] args) {
this.initialize(args);
}
private void initialize(String[] data) {
library.errorHandler = new ErrorHandler();
}
}
I now change the class slightly to
private void initialize(String[] data) {
errorHandler = new ErrorHandler();
}
I declare errorHandler in other classes as follows:
private ErrorHandler errorHandler = TestLibrary.getLibrary().getErrorHandler();
My code ultimately still functions the same when I use the instance of errorHandler
in other classes, but I don’t understand why.
Question 1: Shouldn’t the 2nd case create a new ErrorHandler
that is part of the object TestLibrary.errorHandler
rather than library.errorHandler
?
Question 2: Am I doing something wrong? Could you elaborate?