用java设计一个矩形类(Rect),该类有属性高度和宽度,有计算面积和周长的方法。创建一个高2宽3的矩形对象,输出该矩形的面积和周长
时间: 2024-09-06 12:02:17 浏览: 27
在Java中设计一个矩形类(Rect)首先需要定义类的属性,即高度和宽度。接着,我们需要为矩形类提供两个方法:一个用于计算面积,一个用于计算周长。以下是矩形类的简单实现:
```java
public class Rect {
// 属性高度和宽度
private int height;
private int width;
// 构造方法,创建对象时初始化高度和宽度
public Rect(int height, int width) {
this.height = height;
this.width = width;
}
// 计算面积的方法
public int area() {
return height * width;
}
// 计算周长的方法
public int perimeter() {
return 2 * (height + width);
}
// Getter和Setter方法
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
}
```
创建一个高度为2、宽度为3的矩形对象,并输出该矩形的面积和周长的代码如下:
```java
public class Main {
public static void main(String[] args) {
// 创建矩形对象
Rect rect = new Rect(2, 3);
// 输出矩形的面积和周长
System.out.println("矩形的面积是:" + rect.area());
System.out.println("矩形的周长是:" + rect.perimeter());
}
}
```
执行上述`Main`类中的`main`方法,程序会输出:
```
矩形的面积是:6
矩形的周长是:10
```