代码分析与改错:请指出如下Java代码中存在的错误,并解释原因。注释掉错误语句后,程序输出结果是什么?请解释原因。
abstract class Shape { // 几何图形
public abstract double getArea();
}
class Square extends Shape {
private double height = 0;// 正方形的边长
public Square(double height) {
this.height = height;
}
public double getArea() {
return (this.height * height);
}
}
class Circle extends Shape {
private double r = 0;// 圆的半径
private final static double PI = 3.14;// 圆周率
public Circle(double r) {
this.r = r;
}
public double getArea() {
return (PI * r * r);
}
}
class TestShape {
public static void main(String[] args) {
Shape square = new Square(3);
Shape circle = new Circle(2);
System.out.println(square.getArea());
System.out.println(circle.getArea());
Square sq = (Square) circle;// 报错
System.out.println(sq.getArea());//报错
}
}
修改前运行结果:
9.0
12.56
Exception in thread "main" java.lang.ClassCastException: P159.Circle cannot be cast to P159.Square
at P159.TestShape.main(T1.java:38)
错误原因:Square不能强行转化为Circle
修改后运行结果:
9.0
12.56
原因:正常运行计算正方形和圆的面积