mmk
mmk

Reputation: 505

Is there any difference between these two calls for static method?

In following code, is there any difference between ABC.getSomeNumber(); and getSomeNumber();. I understand having a class name to call static method in the same class seems redundant, but is there any performance issue or some other issue if we use class name explicitly? How are these resolved at compile time ABC.getSomeNumber(); vs getSomeNumber();?

public class ABC {
   public static int getSomeNumber(){
     return 10;
   }

   public static void anotherMethod(){
     ABC.getSomeNumber();
     getSomeNumber();
   } 
}

Upvotes: 1

Views: 106

Answers (3)

LuCio
LuCio

Reputation: 5173

Let's look at the bytecode to see if there is a difference:

Compiled from "ABC.java"
public class playground.ABC {
  public playground.ABC();
    Code:
       0: aload_0
       1: invokespecial #8                  // Method java/lang/Object."<init>":()V
       4: return

  public static int getSomeNumber();
    Code:
       0: bipush        10
       2: ireturn

  public static void anotherMethod();
    Code:
       0: invokestatic  #17                 // Method getSomeNumber:()I
       3: pop
       4: invokestatic  #17                 // Method getSomeNumber:()I
       7: pop
       8: return
}

The description of invokestatic says: The arguments

(...) are used to construct an index into the run-time constant pool of the current class. (...) The run-time constant pool item at that index must be a symbolic reference to a method or an interface method (...), which gives the name (...) of the method as well as a symbolic reference to the class or interface in which the method is to be found. The named method is resolved.

Both calls are reffering to the same item (#17) of the constant pool in the same way. There is no difference in the bytecode whether the static local method getSomeNumber is called qualified or unqualified.

Upvotes: 2

Andy Turner
Andy Turner

Reputation: 140309

No difference in this case.

You would need the name if calling from a different class (either directly, or via a static import).

You can use either form in the same class. It is really down to preference. You may choose to use the class name explicitly if you call similarly-named methods from lots of classes, as that would help you to disambiguate as you read more easily.

There is no impact on performance, as they become the same once compiled.

Upvotes: 3

Shubhendu Pramanik
Shubhendu Pramanik

Reputation: 2751

No there's no difference. ClassName.methodName() is used only when you are calling it from outside of the class.

Upvotes: 1

Related Questions