java 中利用接口数组调用方法的核心做法是:定义一个包含目标方法的接口,让多个类实现该接口,并将这些类的实例存入接口类型的数组中。遍历时直接调用接口方法,jvm 会根据对象实际类型执行对应的重写逻辑。

如何定义支持多态的接口与实现类
需要创建一个接口并声明抽象方法,随后编写两个不同的类来实现该接口,提供各自的方法体。

public interface Shape {
double getArea();
}
public class Circle implements Shape {
private double radius;
public Circle(double r) { this.radius = r; }
public double getArea() { return Math.PI * radius * radius; }
}
public class Rectangle implements Shape {
private double width, height;
public Rectangle(double w, double h) { this.width = w; this.height = h; }
public double getArea() { return width * height; }
}
如何将实现类实例存入数组并遍历调用
创建接口数组时指定类型为接口名,赋值时将子类对象隐式转换为接口对象,通过循环遍历数组并调用方法即可触发多态。
立即学习“Java免费学习笔记(深入)”;

Shape[] shapes = new Shape[2];
shapes[0] = new Circle(5.0);
shapes[1] = new Rectangle(4.0, 6.0);
for (Shape s : shapes) {
System.out.println(s.getArea());
}
当数组元素为 null 时会发生什么
如果接口数组中包含未初始化的 null 元素,在遍历过程中尝试调用其方法会抛出 NullPointerException。必须在调用前进行判空处理或确保数组已完全初始化。


















