Java写一个名为Rectangle的类表示矩形。其成员变量有width、height、color,width和height是double类型,color是String类型。假定所有矩形颜色相同,用一个类变量表示颜色。要求提供构造方法和计算矩形面积的computeArea()方法以及计算矩形周长的Circumference()方法。
时间: 2024-03-25 10:39:59 浏览: 14
好的,下面是一个简单的Java代码实现:
```java
public class Rectangle {
private double width;
private double height;
private static String color;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public static void setColor(String c) {
color = c;
}
public double computeArea() {
return width * height;
}
public double computeCircumference() {
return 2 * (width + height);
}
}
```
这个`Rectangle`类有三个属性:`width`表示宽,`height`表示高,`color`表示颜色(用静态属性表示)。它有一个构造方法,用于初始化`width`和`height`属性。它还有两个方法:`computeArea()`用于计算矩形的面积,`computeCircumference()`用于计算矩形的周长。你可以根据需要来添加其他方法。
相关问题
用java实现设计名为Rectangle的类表示矩形, 成员变量:width和height表示矩形的宽和高,其数据类型为double,默认值是1.0; 成员变量:color表示矩形的颜色,其数据类型为String,默认颜色为白色; 构造方法:无参数的构造方法Rectangle(),其功能是创建默认的矩形; 构造方法:带三个参数的构造方法Rectangle(double width,double height,String color),其功能是创建指定大小和颜色的矩形 成员方法:getWidth()、ge
tHeight()、getColor()分别返回矩形的宽、高和颜色; 成员方法:getArea()返回矩形的面积; 成员方法:getPerimeter()返回矩形的周长; 成员方法:toString()返回矩形的字符串描述,格式为“矩形的宽为x,高为y,颜色为z。”
下面是Java代码实现:
```
public class Rectangle {
private double width;
private double height;
private String color;
// 无参数构造方法
public Rectangle() {
this.width = 1.0;
this.height = 1.0;
this.color = "白色";
}
// 带三个参数的构造方法
public Rectangle(double width, double height, String color) {
this.width = width;
this.height = height;
this.color = color;
}
// 返回矩形的宽
public double getWidth() {
return this.width;
}
// 返回矩形的高
public double getHeight() {
return this.height;
}
// 返回矩形的颜色
public String getColor() {
return this.color;
}
// 返回矩形的面积
public double getArea() {
return this.width * this.height;
}
// 返回矩形的周长
public double getPerimeter() {
return 2 * (this.width + this.height);
}
// 返回矩形的字符串描述
public String toString() {
return "矩形的宽为" + this.width + ",高为" + this.height + ",颜色为" + this.color + "。";
}
}
```
设计一个名为Rectangle 的类表示矩形。这个类包括: • 两个名为width 和height 的double 型数据域,它们分别表示矩形的宽和高。width 和height 的默认值都为1。还有一个名为number的静态变量。这些数据域均定义为pri
vate。
• 一个无参构造方法,创建一个默认宽和高均为1的矩形。
• 一个带参构造方法,创建一个指定宽和高的矩形。
• 两个访问器方法getWidth 和getHeight,分别返回矩形的宽和高。
• 一个名为getArea 的方法返回矩形的面积。
• 一个名为getPerimeter 的方法返回矩形的周长。
• 一个名为increaseNumber 的静态方法,每次被调用时number的值加1。
下面是这个类的代码实现:
```java
public class Rectangle {
private double width;
private double height;
private static int number = 0;
public Rectangle() {
this.width = 1;
this.height = 1;
increaseNumber();
}
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
increaseNumber();
}
public double getWidth() {
return width;
}
public double getHeight() {
return height;
}
public double getArea() {
return width * height;
}
public double getPerimeter() {
return 2 * (width + height);
}
public static void increaseNumber() {
number++;
}
}
```