任务一: (1)建立一个抽象父类Ishape,包括了两个抽象方法,一个是求周长的方法length(),一个是求面积的方法area(); (2)新建一个子类圆Circle继承Ishape (3)新建一个子类矩形Rect继承Ishape (4)新建一个三角形Triangle类继承Ishape (5)新建一个测试类Test,在里面通过上转型对象展示多态性
时间: 2023-12-03 14:43:37 浏览: 220
以下是代码实现:
```java
// Ishape.java
public abstract class Ishape {
public abstract double length();
public abstract double area();
}
// Circle.java
public class Circle extends Ishape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double length() {
return 2 * Math.PI * radius;
}
@Override
public double area() {
return Math.PI * radius * radius;
}
}
// Rect.java
public class Rect extends Ishape {
private double width;
private double height;
public Rect(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double length() {
return 2 * (width + height);
}
@Override
public double area() {
return width * height;
}
}
// Triangle.java
public class Triangle extends Ishape {
private double a;
private double b;
private double c;
public Triangle(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public double length() {
return a + b + c;
}
@Override
public double area() {
double p = (a + b + c) / 2;
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
}
}
// Test.java
public class Test {
public static void main(String[] args) {
Ishape shape1 = new Circle(5);
System.out.println("圆的周长:" + shape1.length());
System.out.println("圆的面积:" + shape1.area());
Ishape shape2 = new Rect(3, 4);
System.out.println("矩形的周长:" + shape2.length());
System.out.println("矩形的面积:" + shape2.area());
Ishape shape3 = new Triangle(3, 4, 5);
System.out.println("三角形的周长:" + shape3.length());
System.out.println("三角形的面积:" + shape3.area());
}
}
```
运行结果:
```
圆的周长:31.41592653589793
圆的面积:78.53981633974483
矩形的周长:14.0
矩形的面积:12.0
三角形的周长:12.0
三角形的面积:6.0
```
可以看到,通过上转型对象展示了多态性,通过一个Ishape类型的变量可以引用Circle、Rect和Triangle类型的对象,且调用它们的方法时会自动调用对应子类的实现。
阅读全文