- 示例代码:
public interface Shape {
double calculateArea();
}
public class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
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 calculateArea() {
return width * height;
}
}
public class Main {
public static void main(String[] args) {
Shape circle = new Circle(5);
Shape rectangle = new Rectangle(4, 6);
System.out.println("Circle area: " + circle.calculateArea());
System.out.println("Rectangle area: " + rectangle.calculateArea());
}
}
- 原理阐述:
- 多态的体现:在上述代码中,
Circle
和Rectangle
都实现了Shape
接口,它们对calculateArea
方法有不同的实现。当我们使用Shape
类型的变量分别指向Circle
和Rectangle
的实例时,调用calculateArea
方法会根据实际对象的类型(即Circle
或Rectangle
)来执行相应的实现,从而体现出不同的行为。
- 背后原理:
- 编译时多态:在Java中,方法调用在编译期是静态绑定的,即根据变量的声明类型来决定调用哪个方法。在
Shape circle = new Circle(5);
中,变量circle
声明为Shape
类型,编译器只知道Shape
接口中有calculateArea
方法。
- 运行时多态:在运行期,Java虚拟机(JVM)会根据对象的实际类型来决定执行哪个方法。当调用
circle.calculateArea()
时,JVM知道circle
实际指向的是Circle
对象,所以会执行Circle
类中重写的calculateArea
方法;同理,对于rectangle.calculateArea()
,会执行Rectangle
类中重写的calculateArea
方法。这种运行时根据对象实际类型来动态绑定方法的机制就是多态在面向接口编程中的体现。