Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why some classes don't need the word "New" when creating its instance?

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.

like image 921
Jason Avatar asked Sep 03 '12 22:09

Jason


1 Answers

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()

like image 184
bmargulies Avatar answered Oct 15 '22 00:10

bmargulies