[34]java中方法调用为后期绑定

public class Shape {
void draw(){}
void earse(){}
}
public class Circle extends Shape {
void draw(){
System.out.println("Circle draw()");
}
void earse(){
System.out.println("Circle earse()");
}
}
public class Square extends Shape {
void draw(){
System.out.println("Square draw");
}
void earse(){
System.out.println("Square earse");
}
}
public class Triangle extends Shape {
void draw(){
System.out.println("Triangle darw");
}
void earse(){
System.out.println("Triangle earse");
}
}
public class Shapes {

public static Shape randShpae(){
switch ((int)(Math.random() * 3)) {
case 0:return new Circle();
case 1:return new Square();
case 2:return new Triangle();
default:
return null;
}
}
/**
*
@param args
*/
public static void main(String[] args) {
Shape[] shapes = new Shape[9];
for(int i = 0;i < shapes.length;++i){
shapes[i] = randShpae();
}

for(int i = 0;i < shapes.length;++i){
shapes[i].draw();
}
}
}

运行结果为:

Triangle darw
Square draw
Triangle darw
Triangle darw
Circle draw()
Square draw
Triangle darw
Square draw
Square draw

当然,这个运行结果是随机的,因为不知道每次得到的shape到底是什么。

说明:

  java中所有的方法调用都采用的是后期绑定技术,除非一个方法被声明为final(final你懂的,不允许重写或覆盖)

  这里的形为跟c++是相同的。


posted @ 2012-03-22 10:10  Marstar  阅读(209)  评论(0编辑  收藏  举报