java多态计算面积
时间: 2024-03-10 14:39:55 浏览: 50
Java中的多态是指同一个方法可以在不同的对象上有不同的实现。在计算面积时,可以定义一个Shape类作为基类,然后定义Rectangle和Triangle类作为Shape类的子类。这两个子类都可以重写Shape类中的计算面积方法,实现不同的计算方式。在使用时,可以定义一个Shape类型的变量,然后将其指向一个Rectangle或Triangle类型的对象,通过调用计算面积方法,就可以实现多态计算面积。
例如,定义Shape类如下:
```java
public abstract class Shape {
public abstract double getArea();
}
```
然后定义Rectangle和Triangle类分别继承Shape类,并重写getArea方法:
```java
public class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double getArea() {
return width * height;
}
}
public class Triangle extends Shape {
private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
@Override
public double getArea() {
return 0.5 * base * height;
}
}
```
最后,在使用时,可以定义一个Shape类型的变量,然后将其指向一个Rectangle或Triangle类型的对象,通过调用计算面积方法,就可以实现多态计算面积:
```java
Shape shape1 = new Rectangle(3, 4);
Shape shape2 = new Triangle(3, 4);
System.out.println("Rectangle area: " + shape1.getArea());
System.out.println("Triangle area: " + shape2.getArea());
```
输出结果为:
```
Rectangle area: 12.0
Triangle area: 6.0
```
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)