java实现编写一个Shape类,具有属性:周长和面积;定义其子类三角形和矩形,分别具有求周长的方法。定义主类E,在其main方法中创建三角形和矩形类的对象,并赋给Shape类的对象a、b,使用对象a、b来测试其特性,具体的代码是什么
时间: 2024-10-27 15:15:18 浏览: 139
在Java中,你可以按照以下步骤来实现这个需求:
首先,我们创建一个基础`Shape`类,包含周长和面积属性以及一个抽象方法来计算形状的周长:
```java
abstract class Shape {
protected double perimeter;
protected double area;
public Shape(double perimeter, double area) {
this.perimeter = perimeter;
this.area = area;
}
// 抽象方法,子类需要覆盖它来提供实际的周长计算
abstract double calculatePerimeter();
}
```
接着,定义两个子类`Triangle`和`Rectangle`,它们继承自`Shape`并提供各自的周长计算:
```java
class Triangle extends Shape {
private double sideA;
public Triangle(double sideA, double base, double height) {
super(calculateTrianglePerimeter(sideA, base), calculateTriangleArea(sideA, base, height));
this.sideA = sideA;
}
private double calculateTrianglePerimeter(double a) {
return a + (a * 2);
}
private double calculateTriangleArea(double a, double b, double h) {
return 0.5 * a * b;
}
}
class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
super(calculateRectanglePerimeter(length, width), calculateRectangleArea(length, width));
this.length = length;
this.width = width;
}
private double calculateRectanglePerimeter(double l, double w) {
return 2 * (l + w);
}
private double calculateRectangleArea(double l, double w) {
return l * w;
}
}
```
最后,在`E`类的`main`方法中创建对象并测试:
```java
public class E {
public static void main(String[] args) {
Triangle triangle = new Triangle(3, 4, 5); // 任意三角形边长
Rectangle rectangle = new Rectangle(5, 7); // 任意矩形长度和宽度
Shape shapeA = triangle; // 将三角形赋值给Shape类型的变量
Shape shapeB = rectangle; // 将矩形赋值给Shape类型的变量
System.out.println("Triangle perimeter: " + shapeA.calculatePerimeter()); // 打印三角形周长
System.out.println("Rectangle perimeter: " + shapeB.calculatePerimeter()); // 打印矩形周长
// 注意,这里会抛出异常,因为Shape类有一个抽象方法calculatePerimeter(),而直接调用shapeA.calculatePerimeter()不会自动调用Triangle版本
}
}
```
阅读全文