定义一个矩形类Rectangle、梯形类Ladder、测试类AreaTest,这三个类处于同一个包com.test中,AreaTest类为主类,在main()方法中创建矩形类和梯形类的相应对象,调用其成员函数计算矩形、梯形的面积
时间: 2024-05-03 15:22:00 浏览: 257
Rectangle类的代码如下:
```java
package com.test;
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 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;
}
}
```
Ladder类的代码如下:
```java
package com.test;
public class Ladder {
private double top;
private double bottom;
private double height;
public Ladder(double top, double bottom, double height) {
this.top = top;
this.bottom = bottom;
this.height = height;
}
public double getTop() {
return top;
}
public void setTop(double top) {
this.top = top;
}
public double getBottom() {
return bottom;
}
public void setBottom(double bottom) {
this.bottom = bottom;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getArea() {
return (top + bottom) * height / 2;
}
}
```
AreaTest类的代码如下:
```java
package com.test;
public class AreaTest {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5, 10);
Ladder ladder = new Ladder(5, 10, 7);
System.out.println("矩形的面积为:" + rectangle.getArea());
System.out.println("梯形的面积为:" + ladder.getArea());
}
}
```
在main()方法中创建了一个长为5、宽为10的矩形对象rectangle和一个上底长为5、下底长为10、高为7的梯形对象ladder,并调用它们的getArea()方法计算面积,最后输出结果。
阅读全文