解决这个问题的方法有很多种,以下是一种常见的解决方法:
public abstract class Object {
// 父类的共有方法和属性
// ...
}
public class Type1 extends Object {
// Type1 类的特定属性和方法
// ...
}
public class Type2 extends Object {
// Type2 类的特定属性和方法
// ...
}
// 其他类型的子类...
Object[] objects = new Object[3];
objects[0] = new Type1();
objects[1] = new Type2();
objects[2] = new Type1();
for (Object obj : objects) {
if (obj instanceof Type1) {
Type1 type1Obj = (Type1) obj;
// 对 Type1 类型的对象进行操作
// ...
} else if (obj instanceof Type2) {
Type2 type2Obj = (Type2) obj;
// 对 Type2 类型的对象进行操作
// ...
}
// 其他类型的对象处理...
}
通过以上的解决方法,我们可以在对象数组中存储不同类型的对象,并且可以根据对象的类型进行特定操作。这样可以方便地管理和处理不同类型的对象。
下一篇:不同类型的方法传递