Why isn't calling a static method by way of an instance an error for the Java compiler?

后端 未结 12 2194
北海茫月
北海茫月 2020-11-22 06:59

I\'m sure you all know the behaviour I mean - code such as:

Thread thread = new Thread();
int activeCount = thread.activeCount();

provokes

12条回答
  •  青春惊慌失措
    2020-11-22 07:51

    The purpose of the instance variable reference is only to supply the type which encloses the static. If you look at the byte code invoking a static via instance.staticMethod or EnclosingClass.staticMethod produces the same invoke static method bytecode. No reference to the instance appears.

    The answer as too why it's in there, well it just is. As long as you use the class. and not via an instance you will help avoid confusion in the future.

提交回复
热议问题