问题
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