What is the difference between ClassName.m () and (new ClassName ()). M () m () - static method

What is the difference between ClassName.m() and (new ClassName()).m() m() is a static method.

+4
source share
4 answers

The difference is that in your second example, you are creating an unnecessary object in memory.

It still calls the same static method for the ClassName class.

It is recommended that you use ClassName.m() to avoid unnecessarily creating an object and provide context to developers indicating that the static method is actually being called.

+6
source

Three things:

  • The second has an additional challenge, which means that it can change the result. It may be bad, maybe not, but it is something to consider. See an example of how this might work.
  • The second creates an additional object. This is bad.
  • The second means that you are calling the method of the object, not the class itself, which confuses the people who read it. This is also bad. See an example of how this can be very bad!

Consider the following: reason 1:

 class ClassName { static int nextId; static int m() { return nextId; } int id; ClassName() { id = nextId; nextId++; } /** C:\junk>java ClassName 2 2 3 */ public static void main(String[] args) { new ClassName(); new ClassName(); System.out.println(ClassName.m()); System.out.println(ClassName.m()); System.out.println((new ClassName()).m()); } } 

Consider the following by adding to reason 2 as indicated in @emory:

 class ClassName { // perhaps ClassName has some caching mechanism? static final List<ClassName> badStructure = new LinkedList<ClassName>(); ClassName() { // Note this also gives outside threads access to this object // before it is fully constructed! Generally bad... badStructure.add(this); } public static void main(String[] args) { ClassName c1 = new ClassName(); // create a ClassName object c1 = null; // normally it would get GC'd but a ref exist in badStructure! :-( } } 

Consider the following: reason 3:

 class BadSleep implements Runnable { int i = 0; public void run() { while(true) { i++; } } public static void main(String[] args) throws Exception { Thread t = new Thread(new BadSleep()); t.start(); // okay t is running - let pause it for a second t.sleep(1000); // oh snap! Doesn't pause t, it pauses main! Ugh! } } 
+2
source

From the point of view of the external observer, there is no difference. Both methods result in a method call that can only do the same thing anyway. You should never do the second, though, since in this case it makes no sense to create an object.

+1
source

If m() is a static method, it is usually recommended to use ClassName.m() , since m() is a ClassName method, not a ClassName object.

0
source

All Articles