【发布时间】:2017-11-01 02:20:58
【问题描述】:
下面我有一个调用两种方法的驱动程序。第一个方法的参数类型是扩展 Polygon 的泛型类型。第二种方法的参数类型是多边形。两者都要求我转换参数才能调用子类方法。哪个更好?为什么我应该使用一个而不是另一个?
public class Driver {
public static void main(String[] args) {
Square s1;
try {
s1 = new Square(new Point(0,0), new Point(0,1), new Point(1,1), new Point(1,0));
}
catch (IllFormedPolygonException e) {
System.out.println(e.toString());
return;
}
System.out.println(s1.toString());
printArea(s1);
printArea2(s1);
}
public static <T extends Polygon> void printArea(T poly) {
System.out.println(poly.getArea());
if (poly instanceof Triangle) {
((Triangle)poly).doTriangleThing();
}
else if (poly instanceof Square) {
((Square)poly).doSquareThing();
}
else {
System.out.println("Is polygon");
}
}
public static void printArea2(Polygon poly) {
System.out.println(poly.getArea());
if (poly instanceof Triangle) {
((Triangle)poly).doTriangleThing();
}
else if (poly instanceof Square) {
((Square)poly).doSquareThing();
}
else {
System.out.println("Is polygon");
}
}
}
【问题讨论】: