views:

137

answers:

2
public class CallingStaticMethod {
public static void method() {
    System.out.println("I am in method");
}
public static void main(String[] args) {
    CallingStaticMethod csm = null;
    csm.method();
   }
}

Can someone explain how the static method is invoked in the above code?

+11  A: 

It's been optimized away by the compiler, simply because having an instance of the class is not necessary. The compiler basically replaces

csm.method();

by

CallingStaticMethod.method();

It's in general also a good practice to do so yourself. Even the average IDE would warn you about accessing static methods through an instance, at least Eclipse does here.

BalusC
I don't think that's it. You can call static methods using instance syntax, whether or not it can be optimized out. I'm a bit surprised by this particular formulation working, but I suppose it makes sense. :-)
T.J. Crowder
it can _always_ be optimized by the compiler, because it is static.
Bozho
Compilers can optimize code in many ways to make it run faster. Without an instance you don't need to allocate/grab heap and so on.
BalusC
@Bozho: Yeah, I suppose that's another way of looking at it. I wouldn't tend to think of it as an *optimization*, but that's just a semantic thing.
T.J. Crowder
I would reword this answer (but I'm not going to go edit it; that would be pushy): I'd say "You can use instance notation to call class methods, even though it's not a good idea. As you've discovered, the instance doesn't matter at all and can even be `null` -- it's the type of the instance variable that determines what the class is, and therefore what class method is called. Avoid doing this."
T.J. Crowder
Fair enough. I extended/reworded a bit.
BalusC
@T.J. Crowder, why not submit your own answer to the question that says that?
Yishai
+3  A: 

Java allows you to use a Class instance to call static methods, but you should not confuse this allowance as if the method would be called on the instance used to call it.

instance.method();

is the same as

Class.method();

Dan
yes, CallingStaticMethod.method() to use the example of the question.
Bruno Rothgiesser
That's it. There was a very distant bell ringing in my head on this; I seem to recall having been bitten by it (I *never* use instances to call class methods.)
T.J. Crowder