java的抽象类的三角形周长_怎么使用Java把抽象类改为接口计算三角形,长方形,圆形的面积?...
时间: 2024-02-27 11:52:57 浏览: 86
对于第一个问题,计算三角形周长的代码如下:
```java
public abstract class Triangle {
protected double a, b, c;
public Triangle(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
public abstract double getPerimeter();
}
public class ConcreteTriangle extends Triangle {
public ConcreteTriangle(double a, double b, double c) {
super(a, b, c);
}
@Override
public double getPerimeter() {
return a + b + c;
}
}
// 使用方法
Triangle t = new ConcreteTriangle(3, 4, 5);
double perimeter = t.getPerimeter();
System.out.println("三角形周长为:" + perimeter);
```
对于第二个问题,把抽象类改为接口,可以定义一个`Shape`接口,其中包含计算面积的方法`getArea()`,然后分别实现三个形状的类,并实现`Shape`接口,代码如下:
```java
public interface Shape {
double getArea();
}
public class Triangle implements Shape {
private double a, b, c;
public Triangle(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public double getArea() {
double p = (a + b + c) / 2;
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
}
}
public class Rectangle implements Shape {
private double width, height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double getArea() {
return width * height;
}
}
public class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
}
// 使用方法
Shape t = new Triangle(3, 4, 5);
double area = t.getArea();
System.out.println("三角形面积为:" + area);
Shape r = new Rectangle(3, 4);
area = r.getArea();
System.out.println("长方形面积为:" + area);
Shape c = new Circle(3);
area = c.getArea();
System.out.println("圆形面积为:" + area);
```
阅读全文