在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中通过接口实现多态性的方法。