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

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

    Why should it be an error? The instance has access to all the static methods. The static methods can't change the state of the instance (trying to is a compile error).

    The problem with the well-known example that you give is very specific to threads, not static method calls. It looks as though you're getting the activeCount() for the thread referred to by thread, but you're really getting the count for the calling thread. This is a logical error that you as a programmer are making. Issuing a warning is the appropriate thing for the compiler to do in this case. It's up to you to heed the warning and fix your code.

    EDIT: I realize that the syntax of the language is what's allowing you to write misleading code, but remember that the compiler and its warnings are part of the language too. The language allows you to do something that the compiler considers dubious, but it gives you the warning to make sure you're aware that it could cause problems.

提交回复
热议问题