所以我开始了,我对数组很糟糕,我制作了一个数组,其中包含未定义数量的超类实例(为简单起见,我们将其称为超级),其中包含几个子类(我们将它们称为 sub1、sub2 和等等)。我想要做的是检查数组,不仅要计算给定子类中有多少个实例;但是例如调用所有子类 sub2 并将他的布尔值之一切换为 false(如果还没有的话);这是通过子类中的方法完成的。
正如我所说,我在这方面很糟糕,所以我什至不确定如何检查对象是否来自给定的类;我检查了超类(子类提供的)中的一个变量,该变量确定它属于哪个子类;我很确定有更好的方法可以做到这一点,但我现在遇到的实际问题是:给定一个由超类对象组成的数组,如何从子类调用方法?甚至有可能吗?
这里是我使用的代码的简化:
Super superArray []; /* Array containing superclass ("Super") objects */
/*
* Method that calls the constructor to create Super objects and
* stores them in the array
* (I didn't even code this yet and I am not sure if the array with
* that definition can contain subclasses from the superclass)
*/
public int getNumSub1 () {
int NumSub1 = 0;
for (int i=1; i < superArray.length; i++) {
if (superArray[i].getSubclass () == 1) {
NumSub1 ++;
}
}
}
/* Repeat this for each subclass */
public void massToggleSub1 () {
for (int i=0; i < superArray.length; i++) {
if (superArray[i].getSubclass() == 1) {
/*
* These following two return error cause such variable and method
* do not exist in the superclass, but in the subclass
*/
if (superArray[i].sub1BooleanState() == false){
superArray[i].sub1ToggleMethod();
}
}
}
}
也许我只是愚蠢,我错过了我不知道如何实现的子类的声明,但老实说,我不知道该怎么做,我被困在这整整三天了;所以我感谢任何帮助。