标签:color csu sys his log think 开发 int nbsp
Think in java P202Once you learn about polymorphism, you can begin to think that everything happens polymorphically. However, only ordinary method calls can be polymorphic.
For example, if you access a field directly, that access will be resolved at compile time, as the following example demonstrates.
一旦你学了多态,你就开始想象所有的东西都可以多态。然而,只有普通的方法可以多态化。例如,如果你直接访问一个字段,该访问将在编译时解决。
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
所以多态只能用于普通方法啦。
虽然这似乎可能是一个令人困惑的问题,但实际上它实际上并没有出现。因为实际开发中我们都将变量设为私有啦。
当果然还有静态方法喽
class StaticSuper { public static String staticGet() { return "Base staticGet()"; } public String dynamicGet() { return "Base dynamicGet()"; } } class StaticSub extends StaticSuper { public static String staticGet() { return "Derived staticGet()"; } public String dynamicGet() { return "Derived dynamicGet()"; } } public class StaticPolymorphism { public static void main(String[] args) { StaticSuper sup = new StaticSub(); // Upcast System.out.println(sup.staticGet()); System.out.println(sup.dynamicGet()); } }
输出:
Base staticGet()
Derived dynamicGet()
静态方法只和类有关啦,和某个对象没有关系啦。
标签:color csu sys his log think 开发 int nbsp
原文地址:http://www.cnblogs.com/alway-july/p/7505322.html