Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to model multiple inheritance objects in Java

i've got the following Problem in a little soccer manager game i'm writing. I've got the classes Person, Player, Coach, Manager. Person is the base Class of the other ones. The Problem is that a Player can also be a Coach and/or a Manager. By adding more Roles (e.g. groundkeeper) i'll get more and more complex - so, how can you implement this efficiently? Isn't there a Pattern for that?

like image 594
themulle Avatar asked Sep 01 '26 15:09

themulle


2 Answers

Don't model the role as a type of person. The Person should have a collection of Roles

public enum Role {
  PLAYER,
  COACH,
  REF 
}

public class Player {
  private final String name;
  private Collection<Role> roles = new ArrayList<Role>();

  public Player(String name) {
    this.name = name;
  }

  public void addRole(Role role) {
    this.roles.add(role);
  }
 }
like image 151
Nick Orton Avatar answered Sep 03 '26 04:09

Nick Orton


I'd have a Role interface whose implementation classes wrapped a Person as a data member. (AbstractRole makes sense here.)

Prefer composition over inheritance, especially in this case.

like image 39
duffymo Avatar answered Sep 03 '26 04:09

duffymo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!