在Java中,如果你需要保持对多个类的数组引用,可以使用接口或抽象类作为数组的元素类型。这样,数组可以存储实现了该接口或继承了该抽象类的所有类的实例。
List
、Set
等集合接口的实现类数组。interface Shape {
void draw();
}
class Circle implements Shape {
@Override
public void draw() {
System.out.println("Drawing a Circle");
}
}
class Square implements Shape {
@Override
public void draw() {
System.out.println("Drawing a Square");
}
}
public class Main {
public static void main(String[] args) {
Shape[] shapes = new Shape[2];
shapes[0] = new Circle();
shapes[1] = new Square();
for (Shape shape : shapes) {
shape.draw();
}
}
}
abstract class Animal {
abstract void makeSound();
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Bark");
}
}
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Meow");
}
}
public class Main {
public static void main(String[] args) {
Animal[] animals = new Animal[2];
animals[0] = new Dog();
animals[1] = new Cat();
for (Animal animal : animals) {
animal.makeSound();
}
}
}
原因:尝试将不兼容的对象添加到数组中。
解决方法:确保所有添加到数组中的对象都实现了相同的接口或继承了相同的抽象类。
原因:在运行时调用方法时,对象的类型与预期不符。
解决方法:使用instanceof
关键字进行类型检查,或者在设计时确保类型的正确性。
if (shape instanceof Circle) {
// 执行特定于Circle的操作
}
通过上述方法,可以有效地管理和操作多个类的数组引用,同时保持代码的灵活性和可扩展性。
领取专属 10元无门槛券
手把手带您无忧上云