用抽象类的方法定义基本几何图形的基类(Shape),然后在 Shape类中定义抽象方法面积的方法getArea() 及边长getLength()的抽象方法 用定义接口类的方法定义基本几何图形的基类(ShapeI),然后在 ShapeI类中定义抽象方法面积的方法getArea() 及边长getLength()的抽象方法 然后定义Shape的派生类Circle(圆),Square(正方形)和Triangle(三角形)。要求通过方法覆盖来计算各种图形的面积和周长。 同样的用ShapeI接口实现圆正方形和三角形的类的计算各种图形的面积和周长.
时间: 2024-02-25 08:58:45 浏览: 78
使用抽象类的方法定义基本几何图形的基类(Shape):
```java
abstract class Shape {
public abstract double getArea(); // 抽象方法,获取面积
public abstract double getLength(); // 抽象方法,获取边长
}
```
使用接口类的方法定义基本几何图形的基类(ShapeI):
```java
interface ShapeI {
double getArea(); // 抽象方法,获取面积
double getLength(); // 抽象方法,获取边长
}
```
定义Shape的派生类Circle(圆),Square(正方形)和Triangle(三角形):
```java
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
public double getLength() {
return 2 * Math.PI * radius;
}
}
class Square extends Shape {
private double side;
public Square(double side) {
this.side = side;
}
public double getArea() {
return side * side;
}
public double getLength() {
return 4 * side;
}
}
class Triangle extends Shape {
private double a, b, c;
public Triangle(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
public double getArea() {
double p = (a + b + c) / 2;
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
}
public double getLength() {
return a + b + c;
}
}
```
使用ShapeI接口实现圆正方形和三角形的类的计算各种图形的面积和周长:
```java
class CircleI implements ShapeI {
private double radius;
public CircleI(double radius) {
this.radius = radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
public double getLength() {
return 2 * Math.PI * radius;
}
}
class SquareI implements ShapeI {
private double side;
public SquareI(double side) {
this.side = side;
}
public double getArea() {
return side * side;
}
public double getLength() {
return 4 * side;
}
}
class TriangleI implements ShapeI {
private double a, b, c;
public TriangleI(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
public double getArea() {
double p = (a + b + c) / 2;
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
}
public double getLength() {
return a + b + c;
}
}
```
这样就可以通过方法覆盖来计算各种图形的面积和周长。
阅读全文