一、多态的缺陷
1、覆盖私有方法
public class PrivateOverride{ private void f(){ print("private f()"); } public static void main(String args[]){ PrivateOverride po=new Derived(); po.f(); } } class Derived extends PrivateOverride{ public void f(){ print("public f()"); } }
private f()
2、如果某个方法为static,则它的行为不具有多态性
class StaticSuper{ public static void staticGet(){ System.out.println("base staticGet()"); } public void dynamicGet(){ System.out.println("base dynamicGet()"); } } class StaticSub extends StaticSuper{ public static void staticGet(){ System.out.println("sub staticGet()"); } public void dynamicGet(){ System.out.println("sub dynamicGet()"); } } public class StaticPolymorphism{ public static void main(String args[]){ StaticSuper sup=new StaticSub(); sup.staticGet(); sup.dynamicGet(); } }
output:
base staticGet()
sub dynamicGet()
二、构造器内部的多态方法的行为
class Glyph{ void draw(){print("Glyph.draw()");} Glyph(){ print("Glyph before draw()"); draw(); print("Glyph after draw()"); } } class RoundGlyph extends Glyph{ private int radius=1; RoundGlyph(r){ radius=r; print("RoundGlyph.RoungGlyph(),radius="+radius); } void draw(){print("RoundGlyph.draw(),radius="+radius);} } public class PolyConstructors{ public static void main(String args[]){ new RoundGlyph(5); } }
Glyph before draw()
RoundGlyph.draw(),radius=0
Glyph after draw()
RoundGlyph.RoundGlyph(),radius=0
原文地址:http://blog.csdn.net/zerountao/article/details/38730195