建一个抽象基类Graph,属性有String型的name和两个抽象方法方法计算周长getPerimeter()和显示图形名称和面积的show()。其派生类有Triangle(等边三角形)和Circle(圆形),利用多态性实现getPerimeter()和show()方法。要求从键盘获取用户输入的圆形半径和等边三角形边长,并分别输出其周长。(文件名Q5.java) 程序运行结果示例如下: 请输入圆形半径:10 图形名称:圆形,周长:62.80 请输入等边三角形边长:20 图形名称:等边三角形,周长:60.00
时间: 2023-06-11 11:09:49 浏览: 120
下面是Q5.java的代码实现:
```java
import java.util.Scanner;
abstract class Graph {
String name;
public abstract double getPerimeter();
public abstract void show();
}
class Triangle extends Graph {
double side;
public Triangle(double side) {
this.side = side;
this.name = "等边三角形";
}
public double getPerimeter() {
return 3 * side;
}
public void show() {
System.out.println("图形名称:" + name + ",周长:" + String.format("%.2f", getPerimeter()));
}
}
class Circle extends Graph {
double radius;
public Circle(double radius) {
this.radius = radius;
this.name = "圆形";
}
public double getPerimeter() {
return 2 * Math.PI * radius;
}
public void show() {
System.out.println("图形名称:" + name + ",周长:" + String.format("%.2f", getPerimeter()));
}
}
public class Q5 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入圆形半径:");
double radius = scanner.nextDouble();
Circle circle = new Circle(radius);
circle.show();
System.out.print("请输入等边三角形边长:");
double side = scanner.nextDouble();
Triangle triangle = new Triangle(side);
triangle.show();
scanner.close();
}
}
```
运行结果:
```
请输入圆形半径:10
图形名称:圆形,周长:62.83
请输入等边三角形边长:20
图形名称:等边三角形,周长:60.00
```
阅读全文