创建3个Java源文件(Example4_1.Java,Rect.java,Ladder.java),用来计算矩形和梯形的面积。
时间: 2024-09-27 15:10:34 浏览: 41
rect_array.rar_RECT _rect_array_rectangular array_矩形阵列
创建三个Java源文件分别用于计算矩形、梯形的面积是非常常见的面向对象编程练习。下面是简化的示例,每个文件包含相关的类定义和方法:
**Example4_1.java** (主程序)
```java
// 主程序,导入需要的类
import java.util.Scanner;
public class Example4_1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入矩形的长和宽:");
double rectLength = scanner.nextDouble();
double rectWidth = scanner.nextDouble();
// 创建矩形对象并计算面积
Rectangle rectangle = new Rectangle(rectLength, rectWidth);
double rectArea = rectangle.calculateArea();
System.out.println("矩形的面积是:" + rectArea);
System.out.println("请输入梯形的上底、下底和高的值:");
double ladderTopBase = scanner.nextDouble();
double ladderBottomBase = scanner.nextDouble();
double ladderHeight = scanner.nextDouble();
// 创建梯形对象并计算面积
Ladder ladder = new Ladder(ladderTopBase, ladderBottomBase, ladderHeight);
double ladderArea = ladder.calculateArea();
System.out.println("梯形的面积是:" + ladderArea);
scanner.close();
}
}
```
**Rect.java**
```java
class Rectangle {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double calculateArea() {
return length * width;
}
}
```
**Ladder.java**
```java
class Ladder extends Rectangle { // 梯形继承自矩形
private double topBase;
public Ladder(double topBase, double bottomBase, double height) {
super(bottomBase, height); // 使用基类构造函数初始化矩形部分
this.topBase = topBase;
}
@Override // 重写父类的calculateArea方法
public double calculateArea() {
return ((topBase + getLength()) / 2) * getHeight(); // 梯形面积公式
}
}
```
阅读全文