rosl 2022-12-12 13:12 采纳率: 100%
浏览 169
已结题

Java题定义接口Shape,包含俩个抽象方法

2.定义接口Shape,包含两个抽象方法getArea()和getCircum(),
分别实现获取图形的面积和周长,抽象方法print()用于输出面积和周长。基于接口Shape定义矩形类Ranctangle和圆类Circle。
圆类包含数据成员有半径,矩形类包含数据成员的有长、宽。
成员通过构造方法进行初始化,每个类都要重写抽象方法getArea()和 getCircum():计算并获取面积和周长,并重写抽象方法print()。
测试类中实例化矩形类Ranctangle和圆类Circle,计算面积和周长,并输出。

  • 写回答

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条)

报告相同问题?

问题事件

  • 系统已结题 1月1日
  • 已采纳回答 12月24日
  • 创建了问题 12月12日

悬赏问题

  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表