抽象类:
/**
* 2021.4.22
* 第八章Java作业
* 代码分析与改错
*/
abstract class Shape { //几何图形
public abstract double getArea();
}
子类:
/**
* 2021.4.22
* 第八章Java作业
* 代码分析与改错
*/
class Square extends Shape {
private double height = 0; //正方形的边长
public Square(double height){
this.height = height;
}
public double getArea(){
return (this.height*this.height);
}
}
子类:
/**
* 2021.4.22
* 第八章Java作业
* 代码分析与改错
*/
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);
}
}
实现:
/**
* 2021.4.22
* 第八章Java作业
* 代码分析与改错
*/
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());
}
}
输出结果:
改错后代码:
/**
* 2021.4.22
* 第八章Java作业
* 代码分析与改错
*/
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());
}
}
运行结果:
错误原因:Square sq=(Square)circle;语句错误,把父类强制转换为子类,必须转换为父类指向的真实子类类型,否则将出现类型转换异常。