用JAVA编写一个Shape类,具有属性:周长和面积;定义其子类三角形和矩形,分别具有求周长的方法。定义主类Test,在其main方法中创建三角形和矩形类的对象,并赋给Shape类的对象a、b,使用对象a、b来测试各自求周长的方法。
时间: 2023-03-25 08:01:50 浏览: 77
好的,我可以回答这个问题。以下是代码示例:
```
public class Shape {
double perimeter;
double area;
}
class Triangle extends Shape {
double side1;
double side2;
double side3;
public double getPerimeter() {
perimeter = side1 + side2 + side3;
return perimeter;
}
}
class Rectangle extends Shape {
double length;
double width;
public double getPerimeter() {
perimeter = 2 * (length + width);
return perimeter;
}
}
public class Test {
public static void main(String[] args) {
Triangle triangle = new Triangle();
triangle.side1 = 3;
triangle.side2 = 4;
triangle.side3 = 5;
Rectangle rectangle = new Rectangle();
rectangle.length = 6;
rectangle.width = 8;
Shape a = triangle;
Shape b = rectangle;
System.out.println("Triangle perimeter: " + a.getPerimeter());
System.out.println("Rectangle perimeter: " + b.getPerimeter());
}
}
```
希望这个代码示例能够帮到您!
阅读全文