简体   繁体   中英

What does a static method/variable actually reference in java if an object has not been initialized?

I understand the basic differences between static and instance methods, but I was wondering this for my CS final as it is not included in our book: what is your code actually referencing when you call a static method?

FooClass.staticMethod();

I am guessing it must initialize the class and then call the method, but that would mean that it isn't really static because its still referencing an object and not the class. Any explanations are appreciated as I really want a greater understanding of this topic, and thanks in advance

FooClass in your example is not an object, it's just an identifier telling the Java compiler what class contains staticMethod . It's true that a program referencing a class causes that class to be loaded and initialized (and also creates an object to represent that class, which is accessible via FooClass.class ), but that doesn't mean that staticMethod is actually an instance method of a class object. It isn't. this has no meaning inside it.

(In fact, at the lowest level, the bytecode instruction for calling a static method is different from the one for calling an instance method.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM