Why does Java bind variables at compile time?

前端 未结 4 592
心在旅途
心在旅途 2020-12-04 14:15

Consider the following example code

class MyClass {
    public String var = \"base\";

    public void printVar() {
        System.out.println(var);
    }
}
         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-04 14:34

    The reason is explained in the Java Language Specification in an example in Section 15.11, quoted below:

    ...

    The last line shows that, indeed, the field that is accessed does not depend on the run-time class of the referenced object; even if s holds a reference to an object of class T, the expression s.x refers to the x field of class S, because the type of the expression s is S. Objects of class T contain two fields named x, one for class T and one for its superclass S.

    This lack of dynamic lookup for field accesses allows programs to be run efficiently with straightforward implementations. The power of late binding and overriding is available, but only when instance methods are used...

    So yes performance is a reason. The specification of how the field access expression is evaluated is stated as follows:

    • If the field is not static:

      ...

      • If the field is a non-blank final, then the result is the value of the named member field in type T found in the object referenced by the value of the Primary.

    where Primary in your case refers the variable derived which is of type MyClass.

    Another reason, as @Clashsoft suggested, is that in subclasses, fields are not overriden, they are hidden. So it makes sense to allow which fields to access based on the declared type or using a cast. This is also true for static methods. This is why the field is determined based on the declared type. Unlike overriding by instance methods where it depends on the actual type. The JLS quote above indeed mentions this reason implicitly:

    The power of late binding and overriding is available, but only when instance methods are used.

提交回复
热议问题