Java – why do some classes not need the word “new” when creating instances?
I'm new to Java One thing that puzzles me is why some classes need new to instantiate, and why others don't need new to instantiate
For example, I'm looking at log4j. It doesn't need a new one
// get a logger instance named "com.foo" Logger logger = Logger.getLogger("com.foo"); logger.setLevel(Level.INFO);
Why do some other courses need new courses? For example, the Employee class:
Employee X = new Employee (John); X.getwork();
wait
Why didn't we say that logger = new logger (...);? Why can we use it even if there is no new one, such as logger Setlevel(), etc
Solution
The only way to create a new object in Java is to use new [1] However, in some classes, you can't say new for yourself. You must call factory methods, which may be static (as in your logger example) or not The author of the class sets the constructor by giving it access other than public
Also note that your example may not involve new objects at all The logger function may return an old object instead of a new object
The following poems by Ogden Nash seem to be somewhat relevant:
This morning I went to the zoo In order to look at the gnu. But the old gnu was dead,and the new gnu,they said,Was too new a new gnu to view.
[1] Use object unless you participate in low-level reflection clone()