Dynamic binding works for methods. Why not for other members [variables]? [duplicate]

风格不统一 提交于 2019-12-20 03:27:12

问题


In the following program. methods are called as per type dynamically. But how about calling variables dynamically. why can't it do so?

class Super {

    public int field = 0;
    public int getField() {
        return field;
    }
}

class Sub extends Super {

    public int field = 1;

    public int getField() {
        return field;
    }

    public int getSuperField() {
        return super.field;
    }
}

public class FieldAccess {

    public static void main(String[] args) {
        Super sup = new Sub(); 
        System.out.println("sup.field = " + sup.field + ", sup.getField() = " + sup.getField());
        Sub sub = new Sub();
        System.out.println("sub.field = " + sub.field + ", sub.getField() = " + sub.getField() + ", sub.getSuperField() = "+ sub.getSuperField());
    }
}

Output:

sup.field = 0, sup.getField() = 1
sub.field = 1, sub.getField() = 1, sub.getSuperField() = 0

here, if sup.method() can be found dynamically, why can't we get sup.variable dynamically?

is it possible? if not why ?

when we have (superclas)animal--->Dog,Cat,lion we call its method say makeNoise() we receive bark or meow... respectively. but why not we ask for its name and get it accordingly?


回答1:


In Java, member variables have static binding because Java does not allow for polymorphic behavior with member variables.

private methods, as they are never inherited and the compiler can resolve calls to any private method at compile time only. Hence static binding.

Secondly, consider the below code..

class SuperClass{
...
public String someVariable = "SuperClass";
...
}

class SubClass extends SuperClass{
...
public String someVariable = "SubClass";
...
}
...
...

SuperClass superClass1 = new SuperClass();
SuperClass superClass2 = new SubClass();

System.out.println(superClass1.someVariable);
System.out.println(superClass2.someVariable);
...

Output:- SuperClass SuperClass

The member variable is resolved based on the declared type of the object reference only, which the compiler is capable of finding as early as at the compile time only and hence a static binding in this case.

In summary, basically Java developers didn't want these checks to happen till Run time and get an exception at that point.




回答2:


As you overrided the super class method.

public int getField() {
        return field;
}


来源:https://stackoverflow.com/questions/17303662/dynamic-binding-works-for-methods-why-not-for-other-members-variables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!