I am new to Java. One thing confuses me is to why some of the classes need new
to instantiate, and why some others do NOT need new
to instantiate.
For example, I am looking at log4j, it does not need new
.
// get a logger instance named "com.foo"
Logger logger = Logger.getLogger("com.foo");
logger.setLevel(Level.INFO);
Why do some other classes need new? For example, an Employee class:
Employee X = new Employee (John);
X.getwork();
etc etc.
Why we did not say , Logger logger = new Logger(...);
? and why were we able to use it even without new
, like logger.setLevel()
, etc.
The only way to create a new object in Java is with new
[1]. However, in some classes, you're not permitted to say new
for yourself, you must call a factory method, which might be static (as with your logger example) or not. The author of a class sets this up by making the constructor(s) have access other than public
.
Also note that your example may not involve a new object at all. That Logger
function might be returning an old object, not a new one.
The following poem by Ogden Nash seems faintly 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] Unless you get involved in low-level reflection, or use Object.clone()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With