Why does Java bind variables at compile time?

前端 未结 4 604
心在旅途
心在旅途 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:41

    While you might be right about performance, there is another reason why fields are not dynamically dispatched: You wouldn't be able to access the MyClass.var field at all if you had a MyDerivedClass instance.

    Generally, I don't know about any statically typed language that actually has dynamic variable resolution. But if you really need it, you can make getters or accessor methods (which should be done in most cases to avoid public fields, anyway):

    class MyClass
    {
        private String var = "base";
    
        public String getVar() // or simply 'var()'
        {
            return this.var;
        }
    }
    
    class MyDerivedClass extends MyClass {
        private String var = "derived";
    
        @Override
        public String getVar() {
            return this.var;
        }
    }
    

提交回复
热议问题