Java缺陷"域于静态方法"[Java编程思想]
程序员文章站
2022-06-07 21:21:50
...
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=0, sub.getField()=1, sub.getSuperField()=0
以上情况比较少见:通常都将所有域设置成private, 因此不能直接访问它们. 另外, 最好不要对基类中的域和导出类中的赋同样的名字
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(); System.out.println(sup.staticGet()); System.out.println(sup.dynamicGet()); } } //output: //Base staticGet() //Derived dynamicGet()
如果某个方法时静态的, 它的行为就不具有多态性. 以上情况也不多见, 因为一般不通过实例调用静态方法.
上一篇: 关于SYSLOG编码的问题file encoding
下一篇: 小明犯了错误冷语去暑