计算由几个不同形状的图形组成的总面积。设要计算的三角形(triangle)、圆(circle)和矩形(rectangle)的面积之和。
2条回答 默认 最新
- CSDN专家-赖老师(软件之家) 2021-07-05 23:51关注
1.定义Shape的抽象类,再定义getArea的抽象方法;
2.定义triangle,circle,rectangle类继承Shape,重写getArea方法即可。public class 继承测试 { /* * 在该类中定义两个方法,一个是 getName,用于使用反射机制获得类名称;另一个是抽象方法 getArea ,用来计算图形的面积。 (2)创建圆形类 * Circle ,继承自 Shape ,并实现抽象方法getArea。 在 Circle * 类的构造方法中获得了圆形的半径,用于在getArea计算圆形的面积。 (3)创建矩形类 Rectangle ,继承自 Shape , 并实现抽象方法 * getArea 。在 Rectangle 类的构造方法中获得了矩形的长和宽,用于在 getArea计算矩形的面积。 * */ public static void main(String[] args) { Shape circle = new Circle(10); System.out.println("类名称是:" + circle.getName()); float s = circle.getArea(); System.out.println("圆的面积=" + circle.getArea()); Shape rect = new Rectangle(10, 20); System.out.println("类名称是:" + rect.getName()); System.out.println("矩形的面积=" + rect.getArea()); s += rect.getArea(); Shape tri = new Triangle(3, 4, 5); System.out.println("类名称是:" + tri.getName()); System.out.println("三角形的面积=" + tri.getArea()); s += tri.getArea(); System.out.println("总面积:"+s); } } abstract class Shape { String getName() { return this.getClass().getName(); } abstract float getArea(); } class Circle extends Shape { float r; public Circle() { }; public Circle(float r) { this.r = r; } @Override float getArea() { return 3.14f * r * r; } } class Rectangle extends Shape { float width; float height; public Rectangle() { } public Rectangle(float width, float height) { this.width = width; this.height = height; } @Override float getArea() { return width * height; } } class Triangle extends Shape // 三角形类 { public Triangle() { } private float sideA, sideB, sideC; private boolean boo; public Triangle(float a, float b, float c) { sideA = a; sideB = b; sideC = c; if (a + b > c && a + c > b && b + c > a) { System.out.println("我是一个三角形"); boo = true; } else { System.out.println("我不是一个三角形"); boo = false; } } public float getArea() { float area; float p = (sideA + sideB + sideC) / 2.0f; area = (float)Math.sqrt(p * (p - sideA) * (p - sideB) * (p - sideC)); System.out.println("三角形面积是:" + area); return area; } }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决评论 打赏 举报无用 1
悬赏问题
- ¥15 求差集那个函数有问题,有无佬可以解决
- ¥15 MATLAB动图问题
- ¥15 【提问】基于Invest的水源涵养
- ¥20 微信网友居然可以通过vx号找到我绑的手机号
- ¥15 寻一个支付宝扫码远程授权登录的软件助手app
- ¥15 解riccati方程组
- ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
- ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
- ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
- ¥50 树莓派安卓APK系统签名