代码分析与改错:请指出如下JAVA代码中存在的错误,并解释原因。注释掉错误语句后,程序输出结果是什么?请解释原因。

抽象类:

/**
 * 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;语句错误,把父类强制转换为子类,必须转换为父类指向的真实子类类型,否则将出现类型转换异常。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值