本帖最后由 许圣建 于 2012-3-4 18:42 编辑
我觉得你这里看不明显,当你有很多同一个父类(接口)的子类同时用一个容器来存储时,你会发现取出来的时候必须重新转型才能使用确切的方法,
那么既然有共同的父类,就可以直接用父类的然后多态了,否则必须挨个判断:instanceof,显然不合理。下面是一个Tij上的例子:- //: c10:Shapes.java
- import com.bruceeckel.simpletest.*;
- class Shape {
- void draw() { System.out.println(this + ".draw()"); }
- }
- class Circle extends Shape {
- public String toString() { return "Circle"; }
- }
- class Square extends Shape {
- public String toString() { return "Square"; }
- }
- class Triangle extends Shape {
- public String toString() { return "Triangle"; }
- }
- public class Shapes {
- private static Test monitor = new Test();
- public static void main(String[] args) {
- // Array of Object, not Shape:
- Object[] shapeList = {
- new Circle(),
- new Square(),
- new Triangle()
- };
- for(int i = 0; i < shapeList.length; i++)
- ((Shape)shapeList[i]).draw(); // 这里
- //monitor.expect后面是预期打印结果
- monitor.expect(new String[] {
- "Circle.draw()",
- "Square.draw()",
- "Triangle.draw()"
- });
- }
- } ///:~
复制代码 |