首页 > 编程语言 > 详细

Java多态

时间:2014-08-21 17:17:54      阅读:317      评论:0      收藏:0      [点我收藏+]

一、多态的缺陷

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

}

ouput:

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);
}
}


output:

Glyph before draw()

RoundGlyph.draw(),radius=0

Glyph after draw()

RoundGlyph.RoundGlyph(),radius=0

Java多态,布布扣,bubuko.com

Java多态

原文:http://blog.csdn.net/zerountao/article/details/38730195

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!