2.定义接口Shape,包含两个抽象方法getArea()和getCircum(),
分别实现获取图形的面积和周长,抽象方法print()用于输出面积和周长。基于接口Shape定义矩形类Ranctangle和圆类Circle。
圆类包含数据成员有半径,矩形类包含数据成员的有长、宽。
成员通过构造方法进行初始化,每个类都要重写抽象方法getArea()和 getCircum():计算并获取面积和周长,并重写抽象方法print()。
测试类中实例化矩形类Ranctangle和圆类Circle,计算面积和周长,并输出。
Java题定义接口Shape,包含俩个抽象方法
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
2条回答 默认 最新
- |__WhoAmI__| 2022-12-12 13:23关注
接口Shape: public interface Shape { double getArea(); double getCircum(); void print(); } 圆类Circle: public class Circle implements Shape { private double radius; public Circle(double radius) { this.radius = radius; } public double getArea() { return Math.PI * radius * radius; } public double getCircum() { return 2 * Math.PI * radius; } public void print() { System.out.println("The area of the circle is: " + getArea()); System.out.println("The circum of the circle is: " + getCircum()); } } 矩形类Ranctangle: public class Rectangle implements Shape { private double length; private double width; public Rectangle(double length, double width) { this.length = length; this.width = width; } public double getArea() { return length * width; } public double getCircum() { return 2 * (length + width); } public void print() { System.out.println("The area of the rectangle is: " + getArea()); System.out.println("The circum of the rectangle is: " + getCircum()); } } 测试类: public class Test { public static void main(String[] args) { Shape circle = new Circle(2.0); circle.print(); Shape rectangle = new Rectangle(2.0, 3.0); rectangle.print(); } } 输出结果: The area of the circle is: 12.566370614359172 The circum of the circle is: 12.566370614359172 The area of the rectangle is: 6.0 The circum of the rectangle is: 10.0
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 1无用
悬赏问题
- ¥15 虚幻5 UE美术毛发渲染
- ¥15 CVRP 图论 物流运输优化
- ¥15 Tableau online 嵌入ppt失败
- ¥100 支付宝网页转账系统不识别账号
- ¥15 基于单片机的靶位控制系统
- ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
- ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
- ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
- ¥15 手机接入宽带网线,如何释放宽带全部速度
- ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测