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

后端 未结 12 2255
北海茫月
北海茫月 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:57

    I just consider this:

    instanceVar.staticMethod();
    

    to be shorthand for this:

    instanceVar.getClass().staticMethod();
    

    If you always had to do this:

    SomeClass.staticMethod();
    

    then you wouldn't be able to leverage inheritance for static methods.

    That is, by calling the static method via the instance you don't need to know what concrete class the instance is at compile time, only that it implements staticMethod() somewhere along the inheritance chain.

    EDIT: This answer is wrong. See comments for details.

提交回复
热议问题