Reputation: 1
I'm trying to practice on inheritance with a hockey team example
public class HockeyPlayer {
private String firstName;
private String lastName;
private String teamName;
public HockeyPlayer(String first, String last) {
firstname = first;
lastName = last;
}
public void print() {
System.out.print(firstName + " " + lastName);
}
}
public class HockeyTeam extends HockeyPlayer {
private String teamName;
public HockeyTeam(String first, String last, String s) {
super(first, last);
teamName = s;
}
public String getTeamName() {
return teamName;
}
public void fight() {
super.print();
System.out.print(" is fighting against ");
}
}
public class HockeyGame {
public static void main(String[] args) {
HockeyTeam team1Player1 = new HockeyTeam("Sidney","Crosby","Pittsburgh Penguins");
HockeyTeam team2Player1 = new HockeyTeam("Jack","Campbell","Toronto Maple Leafs");
team1Player2.fight();
}
}
As you can see, I am also including hockey players fighting each other. Is there a way to make two hockey players fight each other in the HockeyTeam class?
Upvotes: 0
Views: 269
Reputation: 36
Since the main point of this question is about polymorphism, I'll try to give good advice on that first. (I do mean try).
When one class is extending from another, you're saying that classA is a classB. In this case, I don't believe a hockey team is a hockey player. Polymorphism could be used by using abstract classes and having teams extend from them, such as Spokane Chiefs extending from Hockey Team and overriding their methods. SpokaneCheifs would be their own class, in your case you're making each team during runtime.
If you want the two teams to have a connection with eachother during "fights", you could have the fight method take in a HockeyTeam object, such as teamA.fight(teamB). That way teamA would have access to teamB to "fight" with their public getters/setters, I'm not sure how you want them to fight, it's common using a RNG to decide a winner and any damages.
Also, I like how you used a DVC, but unless you know there will be a case where you'll use a player with a blank name, or create it during runtime with setters; it's better to delete it and use your EVCs. If you have a Explicit Value Constructor, Java will not create a Default Value Constructor unless you specify for it.
Upvotes: 1