阅读量:128
在Java中,多态性是通过继承和接口实现的。要实现多态性,你需要遵循以下步骤:
- 定义一个接口:首先,你需要定义一个接口,该接口包含你想要实现多态性的方法。例如,我们创建一个名为
Shape的接口,它有一个名为area()的方法。
public interface Shape {
double area();
}
- 创建实现类:接下来,为接口创建多个实现类。这些类将实现接口中定义的方法。例如,我们创建两个类
Circle和Rectangle,它们分别表示圆形和矩形。
public class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double area() {
return Math.PI * Math.pow(radius, 2);
}
}
public class Rectangle implements Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double area() {
return width * height;
}
}
- 使用多态性:现在你可以在代码中使用多态性。你可以创建一个
Shape类型的引用,然后将其指向Circle或Rectangle对象。当你调用area()方法时,将根据实际的对象类型调用相应的方法实现。
public class Main {
public static void main(String[] args) {
Shape shape1 = new Circle(5);
Shape shape2 = new Rectangle(4, 6);
System.out.println("Circle area: " + shape1.area());
System.out.println("Rectangle area: " + shape2.area());
}
}
输出结果:
Circle area: 78.53981633974483
Rectangle area: 24.0
这就是如何在Java中通过接口实现多态性的方法。