本关任务:定义一个矩形Rectangle 类和 三角形 Triangle类,都继承Shape类,在这两个类中分别定 X一个名为 area 的方法,实现计算该形状面积的功能(Shape类已经定义完成,可以在 Shape.java 文件直看相应代码)。
时间: 2024-10-24 11:12:06 浏览: 90
在Java中,为了定义一个矩形Rectangle类和一个三角形Triangle类,我们可以按照面向对象的设计原则创建一个Shape作为它们的共同父类,并在这个父类中定义一个抽象方法`area()`用于计算面积。下面是一个简单的例子:
首先,假设我们已经有了一个Shape接口(如果还没有,可以创建一个Shape.java文件):
```java
// Shape.java
public abstract class Shape {
public abstract double getArea();
}
```
然后创建Rectangle类,继承Shape并实现`getArea()`方法:
```java
// Rectangle.java
import java.util.Scanner;
public class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double getArea() {
return width * height;
}
// 可选:添加getter和setter方法
public double getWidth() { return width; }
public void setWidth(double width) { this.width = width; }
public double getHeight() { return height; }
public void setHeight(double height) { this.height = height; }
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter rectangle dimensions:");
double width = scanner.nextDouble();
double height = scanner.nextDouble();
Rectangle rectangle = new Rectangle(width, height);
System.out.printf("Rectangle area: %.2f\n", rectangle.getArea());
}
}
```
接着,创建Triangle类,同样继承Shape并实现`getArea()`方法:
```java
// Triangle.java
public class Triangle extends Shape {
private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
@Override
public double getArea() {
return 0.5 * base * height;
}
// 可选:添加getter和setter方法
public double getBase() { return base; }
public void setBase(double base) { this.base = base; }
public double getHeight() { return height; }
public void setHeight(double height) { this.height = height; }
// 主要是示例,实际项目中可能不在main方法中创建Triangle实例
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter triangle dimensions:");
double base = scanner.nextDouble();
double height = scanner.nextDouble();
Triangle triangle = new Triangle(base, height);
System.out.printf("Triangle area: %.2f\n", triangle.getArea());
}
}
```
现在,你可以创建Rectangle和Triangle对象,通过Shape类型的引用调用它们各自的getArea()方法,这体现了多态性。
阅读全文