抽象类的概念:通过创建抽象类形状Shape,分别计算圆、长方形、三角形的面积和周长:Shape类中定义将来子类可能会用到的属性和三个重载的构造方法以及求周长getper()和求面积area()的抽象方法。分别创建圆、长方形、三角形继承抽象类,实现求周长和求面积的计算。在主类中分别计算圆、长方形、三角形的面积和周长。
t = (a+b+c)/2.0;
double s = Math.sqrt(t*(t-a)(t-b)(t-c));
抽象类的概念Java类的创建
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
1条回答 默认 最新
关注 public abstract class Shape { protected List<Double> lengthList = new ArrayList<>(); public Shape(double length) { lengthList.add(length); } public Shape(double length1, double length2) { lengthList.add(length1); lengthList.add(length2); } public Shape(double length1, double length2, double... more) { lengthList.add(length1); lengthList.add(length2); if (more != null) { for (double length : more) { lengthList.add(length); } } } /** * 计算周长 * * @return */ public abstract double getper(); /** * 计算面积 * * @return */ public abstract double area(); } public class Circle extends Shape { public Circle(double radius) { super(radius); } @Override public double getper() { return 2 * Math.PI * this.lengthList.get(0); } @Override public double area() { return Math.PI * this.lengthList.get(0) * this.lengthList.get(0); } } public class Rectangle extends Shape { public Rectangle(double length, double width) { super(length, width); } @Override public double getper() { return (this.lengthList.get(0) + this.lengthList.get(1)) * 2; } @Override public double area() { return this.lengthList.get(0) * this.lengthList.get(1); } } public class Triangle extends Shape { public Triangle(double length1, double length2, double length3) { super(length1, length2, length3); } @Override public double getper() { return this.lengthList.get(0) + this.lengthList.get(1) + this.lengthList.get(2); } @Override public double area() { Double a = this.lengthList.get(0); Double b = this.lengthList.get(1); Double c = this.lengthList.get(2); double t = (a + b + c) / 2.0; double s = Math.sqrt(t * (t - a) * (t - b) * (t - c)); return s; } } public class Main { public static void main(String[] args) { Circle circle = new Circle(1); System.out.printf("圆形周长:%s,面积:%s\n", circle.getper(), circle.area()); Rectangle rectangle = new Rectangle(3, 4); System.out.printf("长方形周长:%s,面积:%s\n", rectangle.getper(), rectangle.area()); Triangle triangle = new Triangle(3, 4, 5); System.out.printf("三角形周长:%s,面积:%s\n", triangle.getper(), triangle.area()); } }
输出如下:
圆形周长:6.283185307179586,面积:3.141592653589793 长方形周长:14.0,面积:12.0 三角形周长:12.0,面积:6.0
有帮助请采纳。
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 乌班图ip地址配置及远程SSH
- ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
- ¥15 PSPICE制作一个加法器
- ¥15 javaweb项目无法正常跳转
- ¥15 VMBox虚拟机无法访问
- ¥15 skd显示找不到头文件
- ¥15 机器视觉中图片中长度与真实长度的关系
- ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
- ¥15 java 的protected权限 ,问题在注释里
- ¥15 这个是哪里有问题啊?