I’m having some trouble with structure.
I have several objects of classes which extend an Entity class, some of these classes overwrite a function A() from the Entity class, requiring a certain input (ex. A(int input)).
Is there any way i can call the function A() of all the objects at the same time(meaning, not having seperate lists for every class)?
I’m now using an arrayList(entities) to store all the objects and typecast them in a for-loop. This seems rather messy and im pretty sure i’m misunderstanding some basic principles of OOP.
for (int i=0;i<entities.size();i++) {
Entity entityPre = (Entity) entities.get(i);
if (entityPre instanceof subClass) {
subClass entity= (subClass) entityPre;
entity.A(int Input);
}else{
entityPre.A();
}
}
Any help would be much appriciated.
You are not really overriding
A()as you changed the method arguments hence changing the method signature.Therefore, you cannot use the ‘regular’ overriding mechanisms and you are stuck with your current implementation.
If you add the method argument to your base class (even though it is not using it), you can override the method properly and simplify your loop content. But personally, I would only perform this modification is the additional argument makes any sense to the base class!