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

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

    Basically I believe the Java designers made a mistake when they designed the language, and it's too late to fix it due to the compatibility issues involved. Yes, it can lead to very misleading code. Yes, you should avoid it. Yes, you should make sure your IDE is configured to treat it as an error, IMO. Should you ever design a language yourself, bear it in mind as an example of the kind of thing to avoid :)

    Just to respond to DJClayworth's point, here's what's allowed in C#:

    public class Foo
    {
        public static void Bar()
        {
        }
    }
    
    public class Abc
    {
        public void Test()
        {
            // Static methods in the same class and base classes
            // (and outer classes) are available, with no
            // qualification
            Def();
    
            // Static methods in other classes are available via
            // the class name
            Foo.Bar();
    
            Abc abc = new Abc();
    
            // This would *not* be legal. It being legal has no benefit,
            // and just allows misleading code
            // abc.Def();
        }
    
        public static void Def()
        {
        }
    }
    

    Why do I think it's misleading? Because if I look at code someVariable.SomeMethod() I expect it to use the value of someVariable. If SomeMethod() is a static method, that expectation is invalid; the code is tricking me. How can that possibly be a good thing?

    Bizarrely enough, Java won't let you use a potentially uninitialized variable to call a static method, despite the fact that the only information it's going to use is the declared type of the variable. It's an inconsistent and unhelpful mess. Why allow it?

    EDIT: This edit is a response to Clayton's answer, which claims it allows inheritance for static methods. It doesn't. Static methods just aren't polymorphic. Here's a short but complete program to demonstrate that:

    class Base
    {
        static void foo()
        {
            System.out.println("Base.foo()");
        }
    }
    
    class Derived extends Base
    {
        static void foo()
        {
            System.out.println("Derived.foo()");
        }
    }
    
    public class Test
    {
        public static void main(String[] args)
        {
            Base b = new Derived();
            b.foo(); // Prints "Base.foo()"
            b = null;
            b.foo(); // Still prints "Base.foo()"
        }
    }
    

    As you can see, the execution-time value of b is completely ignored.

    0 讨论(0)
  • 2020-11-22 07:50

    Probably you can change it in your IDE (in Eclipse Preferences -> Java -> Compiler -> Errors/Warnings)

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 07:54

    It isn't an error because it's part of the spec, but you're obviously asking about the rationale, which we can all guess at.

    My guess is that the source of this is actually to allow a method in a class to invoke a static method in the same class without the hassle. Since calling x() is legal (even without the self class name), calling this.x() should be legal as well, and therefore calling via any object was made legal as well.

    This also helps encourage users to turn private functions into static if they don't change the state.

    Besides, compilers generally try to avoid declaring errors when there is no way that this could lead to a direct error. Since a static method does not change the state or care about the invoking object, it does not cause an actual error (just confusion) to allow this. A warning suffices.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题