版权声明:就是码字也不容易啊 https://blog.csdn.net/qq_40946921/article/details/84445218
设计一个名为Rectangle的类表示矩形。这个类包括:
- 两个名为width和height的double型数据域,它们分别表示矩形的宽和高。width和height的默认值为1
- 创建默认矩形的无参构造函数
- 一个创建width和height为指定值的矩形的构造方法
- 一个名为getArea()的方法返回这个矩形的面积
- 一个名为getPerimeter()的方法返回周长
- width和height均为私有变量,请增加两个访问器访问这两个变量;并在Rectangle类中再增设一个私有静态整型变量numberOfObjects,用来统计该类所实例化的对象个数;Rectangle类的包名为geo;测试程序的包名为自己的姓名倒序(例如ping.jin.xi)。
画出UML图并实现,写一个测试程序,创建两个Rectangle对象——一个宽4高40,另一个宽3.5高35.9,输出它们的相关信息
UML:
运行:
代码:
类代码:
package geo;
public class Rectangle {
private double width=1,height=1;
public static int numberOfObjects=0;
public Rectangle(){
numberOfObjects++;
}
public Rectangle(double width,double height){
this.width=width;
this.height=height;
numberOfObjects++;
}
public double getArea(){
return width*height;
}
public double getPerimeter(){
return (width+height)*2;
}
public double getWidth(){
return width;
}
public double getHeight(){
return height;
}
}
测试代码:
package hao.xing.fu;
import geo.Rectangle;
public class Test {
public static void main(String[] args){
Rectangle rectangle1=new Rectangle(4,40);
Rectangle rectangle2=new Rectangle(3.5,35.9);
System.out.println("矩形1:宽:"+rectangle1.getWidth()+" 高:"+rectangle1.getHeight()+" 面积:"+rectangle1.getArea()+" 周长:"+rectangle1.getPerimeter());
System.out.println("矩形2:宽:"+rectangle2.getWidth()+" 高:"+rectangle2.getHeight()+" 面积:"+rectangle2.getArea()+" 周长:"+rectangle2.getPerimeter());
}
}