game character class design, inheritance or composition?
java
Solution
What I would do is to use inheritance for the classes + Interfaces if there is an option for a combination of properties (for example, if you have a WarriorKing class).
If you want to enjoy the properties of both types in case of something like WarriorKing you can do something like that:
class Character { ... }
interface Warrior {...}
interface King {...}
abstract class KingImpl extends Character implements King
abstract class WarriorImpl extends Character implements Warrior
And then you combine everything:
class WarriorKing extends Character implements Warrior, King {
private King kingImpl;
private Warrior warriorImpl;
public WarriorKing() {
kingImpl = new KingImpl();
warriorImpl = new WarriorImpl();
}
Now lets say you have a method `kill()` in the Warrior interface which needs to be implemented by each implementing class (WarriorKing must implement it), and is already implemented in the abstract WarriorImpl class, you can do something like:
class WarriorKing extends Character implements Warrior, King {
private King kingImpl;
private Warrior warriorImpl;
public WarriorKing() {
kingImpl = new KingImpl();
warriorImpl = new WarriorImpl();
}
public void kill() {
this.warriorImpl.kill()
}
}
This way you enjoy all the worlds by having everything implemented once, having a modular class design and you can enjoy any composition of characters you might need. Good luck!
Problem
I am trying to create the character class for a game. About the character class: -It has different characters, for example warrior, shooter, king. -Each has different properties for example attack, defense. My question here is should I use Inheritance or composition? I have a Character Class, then should I create warrior class and extends character class or should I just put an identifier like String ID ="Warrior" in the Character class?