I’m trying to create a game using the best practices to my knowledge.
I have:
- a
VisibleObjectwith aprotected void draw(Canvas c)function - a
MapTilethatextends VisibleObjectto draw itself. - a
Mapclass that contains a LinkedList of MapTiles,tiles.
In the Map class i wanted a loop like this:
public void draw(Canvas c){
for(MapTile tile : tiles){
tile.draw(c);
}
}
But i realised i could not call draw upon each tile because it’s a protected method in VisibleObject.
I can think of 3 possible solutions:
- Just change
protectedtopublicinVisibleObject. - Create a public method of MapTile that just calls
super.draw(c)(I think that’s valid syntax?) - change the for loop in Map to something like this, which i believe would make it valid.
New Loop:
MapTile current;
for(MapTile tile : tiles){
current = tile;
current.draw(c);
}
Which solution would be better programming practice?
I would go for version 2. Version 1 would introduce access modifiers in the parent that perhaps should not be there (e.g. going from
protectedtopublic), while version 3 does not make much sense, since you are still using an instance ofMapTile(even if it did, it looks awkward and unnatural).If any of the children of a class need to expose a protected method of the parent the best idea is to create a public method that calls the parent method.