使用继承时,您可以创建两个继承自类
A
的类 B
和 C
。然后,您可以创建一个 C
数组来存储其中任意一个 - C[]
。
但是,当使用组合时,数组必须是什么类型才能存储这两种类型?
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
}
}
使用组合时,您必须将实体存储为字段:
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;
}
}
这里只能存储实体。所以只需添加player.entity/monster.entity或其他什么。