根据下面的继承关系,用 java 代码实现 (1) Circle 类(圆形) 属性:半径;方法:1求周长、求面和 (2)Rect 类(矩形 求周- (3) Square 类(正方形),属性:边长;方法:求周长、求面积
时间: 2024-10-11 22:15:29 浏览: 70
Java:使用抽象类定义一个“形状类”,能够计算周长和面积。
在 Java 中,我们可以按照继承结构创建这三个类,并实现相应的属性和方法。首先,我们创建一个 `Shape` 接口作为基础类型:
```java
// Shape接口
public interface Shape {
double getArea();
double getPerimeter();
}
```
然后分别实现 `Circle`, `Rect`, 和 `Square` 类,它们都继承自 `Shape` 并提供各自特有的属性和方法:
```java
// Circle类
public class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
@Override
public double getPerimeter() {
return 2 * Math.PI * radius;
}
}
// Rect类
public class Rect implements Shape {
private double width;
private double height;
public Rect(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double getArea() {
return width * height;
}
@Override
public double getPerimeter() {
return 2 * (width + height);
}
}
// Square类
public class Square extends Rect implements Shape {
public Square(double sideLength) {
super(sideLength, sideLength); // 使用边长作为宽度和高度
}
}
```
现在你可以使用这些类创建实例并调用它们的方法:
```java
public static void main(String[] args) {
Circle circle = new Circle(5);
System.out.println("Circle area: " + circle.getArea());
System.out.println("Circle perimeter: " + circle.getPerimeter());
Rect rect = new Rect(4, 6);
System.out.println("Rect area: " + rect.getArea());
System.out.println("Rect perimeter: " + rect.getPerimeter());
Square square = new Square(3);
System.out.println("Square area: " + square.getArea());
System.out.println("Square perimeter: " + square.getPerimeter());
// 测试 Square 类的多态
Shape shape = square; // 这里 shape 可以同时处理 Square 或者其他实现了 Shape 的类
System.out.println("Square area as a Shape: " + shape.getArea());
System.out.println("Square perimeter as a Shape: " + shape.getPerimeter());
}
```
阅读全文