I have an arraylist of entities. The Entity class has
public void update(int delta, Level level, ArrayList<Entity> entities){
//do stuff
}
a subclass of entity, Player, has a function overriding it
public void update(int delta, Level level, ArrayList<Entity> entities){
//do player specific stuff
super.update(delta, level, entities);
}
when I call the player objects update function from an arraylist of entities, like this:
for(Entity entity : entities) //contains an object of Player
entity.update(delta, level, entities);
it calls the entity function directly and the player specific stuff doesnt happen, however if I call it like this:
((Player)entities.get(0)).update(delta, level, entities);
it does. I thought I understood the problem but I tried the following code
private static class Foo{
public void print(){
System.out.println("I AM FOO");
}
}
private static class Bar extends Foo{
public void print(){
System.out.println("i am bar");
super.print();
}
}
public static void main(String[] args){
ArrayList<Foo> foos = new ArrayList<Foo>();
foos.add(new Foo());
foos.add(new Bar());
for(Foo leFoo: foos)
leFoo.print();
}
and it actually calls the print function from Bar when the object is a bar. I’m kinda lost at this point.
Since you have multiple Level classes, you have to ensure that the
Player.update()method signature references the correct one (in order to override successfully):