编写Java应用程序,创建一个矩形类,类中私有成员属性有长和宽,有成员函数计算面积和周长,创建对象时可对长和宽赋值,要求计算输出其面积和周长,输出矩形长和宽的值。
时间: 2024-03-11 10:17:26 浏览: 91
以下是Java代码实现:
```java
public class Rectangle {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double getLength() {
return length;
}
public double getWidth() {
return width;
}
public double getArea() {
return length * width;
}
public double getPerimeter() {
return 2 * (length + width);
}
public void printInfo() {
System.out.println("矩形长:" + length);
System.out.println("矩形宽:" + width);
System.out.println("矩形面积:" + getArea());
System.out.println("矩形周长:" + getPerimeter());
}
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5, 10);
rectangle.printInfo();
}
}
```
输出结果:
```
矩形长:5.0
矩形宽:10.0
矩形面积:50.0
矩形周长:30.0
```
阅读全文