When using inheritance, you can create two classes A and B that inherit from class C. You can then create an array of C to store either of these -- C[].
However, when using composition, what type would an array have to be to store either of these types?
class Entity {
public int id;
public Entity() {
this.id = 0;
}
}
class Player extends Entity {
public Player() {
this.id = 1;
}
}
class Monster extends Entity {
public Monster() {
this.id = 2;
}
}
public class Main {
public static void main(String[] args) {
Entity[] entities = new Entity[2];
entities[0] = new Player(); // id == 1
entities[1] = new Monster(); // id == 2
}
}
When using composition, you'd have to store Entity as a field:
class Entity {
public int id;
public Entity() {
this.id = 0;
}
}
class Player {
Entity entity;
public Player() {
this.entity = new Entity();
this.entity.id = 1;
}
}
class Monster {
Entity entity;
public Monster() {
this.entity = new Entity();
this.entity.id = 2;
}
}
public class Main {
public static void main(String[] args) {
Player player = new Player();
Monster monster = new Monster();
Entity[] entities = new Entity[2];
// TODO: won't work! what type?
entities[0] = player;
entities[1] = monster;
}
}
You can only store entities in here. So just add player.entity/monster.entity or whatever.