在TIJ中 RTTI有这样的一个例子。
//: c10:Shapes.java
// From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002
// www.BruceEckel.com. See copyright notice in CopyRight.txt.
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(); // Must cast
monitor.expect(new String[] {
"Circle.draw()",
"Square.draw()",
"Triangle.draw()"
});
}
} ///:~
一个object 数组,里面保存的是shape的子类,但在调用各自的draw()时,需要这样的形式:((Shape)shapeList[i]).draw(); 即强制向下类型转换,以告诉数组中保存的是shape对象。
我就不明白了shape到circle,square等是自动装换的,由于多态性的原理。 但shape不也是object的一个子类吗?为何object 不可以自动转换成shape?而需要手动的表明那是个shape对象。
//: c10:Shapes.java
// From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002
// www.BruceEckel.com. See copyright notice in CopyRight.txt.
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(); // Must cast
monitor.expect(new String[] {
"Circle.draw()",
"Square.draw()",
"Triangle.draw()"
});
}
} ///:~
一个object 数组,里面保存的是shape的子类,但在调用各自的draw()时,需要这样的形式:((Shape)shapeList[i]).draw(); 即强制向下类型转换,以告诉数组中保存的是shape对象。
我就不明白了shape到circle,square等是自动装换的,由于多态性的原理。 但shape不也是object的一个子类吗?为何object 不可以自动转换成shape?而需要手动的表明那是个shape对象。
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货