To summarize my problem: I'd like to write an abstract class called Player and have different non-abstract "role" classes extend it. So far so good. I'd also like every sub-class of Player to contain a variable that displays its individual name, and a method to return this name. Kinda like this:
public class Game {
// main and everything else happens here
Player testrole = new TestRole();
System.out.print(testrole.getName());
}
public abstract class Player {
// here I'm trying to accumulate all methods that apply for every Player, regardless of their role
abstract String getName();
}
public class TestRole extends Player {
// every role class extends the basic Player methods by individual, role-specific methods.
private String name = "Test Role";
public String getName() {
return name;
}
}
Now, this works fine and all, but I have 16 different roles and in order to keep my code "DRY", I don't want to repeat myself by giving each role class it's own name variable and getName()-method, the latter of which will look exactly the same for each role class in the end.
Now obviously this won't work:
public abstract class Player {
private String name;
public String getName() {
return this.name;
}
}
... because there would be only one name variable and no individual values for every sub-class, and neither will this:
public abstract class Player {
private String name;
public Player(String name) {
this.name = name;
}
}
... because I'm calling the constructor of TestRole in Game, not the constructor of Player.
If anybody could help me out with this one, I'd be really grateful!