日期:2014-05-20  浏览次数:20722 次

小弟请求
Java code

//: polymorphism/FieldAccess.java
// Direct field access is determined at compile time.

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(); // Upcast
    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());
  }
} 


 结果为:

sup.field = 0, sup.getField() = 1
sub.field = 1, sub.getField() = 1, sub.getSuperField() = 0
但是我不明白为什么 第一个sup.field为什么等于0啊

------解决方案--------------------
Java code
 Super sup = new sub(); //因为Super这个是父类,所以 sup.field 调用的是 field = 0

------解决方案--------------------
字段没有多态,但方法有多态。