有参的构造方法 计算矩形面积和周长-2019.3.11

新建Rectangle类;

代码如下:

package application;

    class Rec{
    double width;
    double height;
    public Rec(double w,double h){
           width=w;
           height=h;
           }
    
    public void computeCircum(){
    double circum=2*(width+height);
    System.out.println("该矩形的周长为"+circum);
    }
    
    public void computArea(){
    double area=width*height;
    System.out.println("该矩形的面积为"+area);
    }
    
    }

    
    public class Rectangle{
    public static void main(String[] args){
    Rec output=new Rec(60,50);
    output.computeCircum();
    output.computArea();
    }
    }
   

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我来为您设计一个Circle类,代码如下: ```python class Circle: def __init__(self, radius, color): self.radius = radius self.color = color def get_radius(self): return self.radius def get_color(self): return self.color def set_radius(self, radius): self.radius = radius def set_color(self, color): self.color = color def get_area(self): return round(3.14 * (self.radius ** 2), 2) def get_perimeter(self): return round(2 * 3.14 * self.radius, 2) ``` 在Circle类中,我们定义了两个属性:半径和颜色。我们还定义了构造方法`__init__`,它将半径和颜色作为数,并将其赋值给对应的属性。此外,我们还定义了一些获取和设置属性的方法,以及计算圆的面积周长的方法。 为了验证Circle类的功能,我们可以编写以下测试程序: ```python # 创建一个圆对象 circle = Circle(5, "red") # 获取圆的半径和颜色 print("圆的半径为:", circle.get_radius()) print("圆的颜色为:", circle.get_color()) # 修改圆的半径和颜色 circle.set_radius(7) circle.set_color("blue") print("修改后的圆的半径为:", circle.get_radius()) print("修改后的圆的颜色为:", circle.get_color()) # 计算圆的面积周长 print("圆的面积为:", circle.get_area()) print("圆的周长为:", circle.get_perimeter()) ``` 运行上述程序,输出结果如下: ``` 圆的半径为: 5 圆的颜色为: red 修改后的圆的半径为: 7 修改后的圆的颜色为: blue 圆的面积为: 153.94 圆的周长为: 43.98 ``` 从输出结果可以看出,Circle类的功能正常,可以正确地计算圆的面积周长

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值