. 定义矩形类Rectangle,含长、宽属性,静态属性ID; 定义两个构造方法,一个默认,一个能初始化长宽属性; 定义求面积、求周长方法,能返回计算结果; 定义长宽属性访问方法和设置方法(称为JavaBean); 定义toString()方法,返回对象信息; 定义静态方法,获取静态属性ID; 定义静态初始化块,设置ID属性; 主类main方法中定义不同类对象,应用所有方法。
时间: 2024-02-19 20:58:52 浏览: 123
定义一个名为rectangle 的矩形类,其属性数据为矩形左上角和右上角的点的坐标能计算矩形的面积
5星 · 资源好评率100%
好的,以下是矩形类Rectangle的代码实现:
```java
public class Rectangle {
private double length;
private double width;
private static int ID;
public Rectangle() {
this.length = 0;
this.width = 0;
}
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getArea() {
return length * width;
}
public double getPerimeter() {
return 2 * (length + width);
}
public static int getID() {
return ID;
}
static {
ID = 1000;
}
@Override
public String toString() {
return "Rectangle [length=" + length + ", width=" + width + "]";
}
}
```
在主类中可以应用所有方法:
```java
public class Main {
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle(3, 4);
r1.setLength(5);
r1.setWidth(6);
System.out.println("Rectangle r1's area is: " + r1.getArea());
System.out.println("Rectangle r1's perimeter is: " + r1.getPerimeter());
System.out.println("Rectangle r1's ID is: " + Rectangle.getID());
System.out.println("Rectangle r1's info is: " + r1.toString());
System.out.println("Rectangle r2's area is: " + r2.getArea());
System.out.println("Rectangle r2's perimeter is: " + r2.getPerimeter());
System.out.println("Rectangle r2's ID is: " + Rectangle.getID());
System.out.println("Rectangle r2's info is: " + r2.toString());
}
}
```
输出结果如下:
```
Rectangle r1's area is: 30.0
Rectangle r1's perimeter is: 22.0
Rectangle r1's ID is: 1000
Rectangle r1's info is: Rectangle [length=5.0, width=6.0]
Rectangle r2's area is: 12.0
Rectangle r2's perimeter is: 14.0
Rectangle r2's ID is: 1000
Rectangle r2's info is: Rectangle [length=3.0, width=4.0]
```
阅读全文