Below is a snippet of my code and I can’t decide whether or not it is an example of Polymorphism.
Class hierarchy 1
Within my Player class (This is a subclass of Character) there is a method called showStats().
public String showStats(){ // Displays all current stats regarding the player.
String stats = "<html><br>Name: "+ getName()+ "<br>Type: "+ getCharacterType() + "<br>Health: "+ getHealth() +"<br>Weapon Equipped: "+ getWeaponEquippedName()+"<br>Miles Walked: "+getWalked()+"<br>"+showInventory()+"<br>Level Completed: "+getLevelCompleted();
return stats;
}
This method is overridden within the Magician and Warrior classes due to exclusive statistics only Warriors and Magicians would possess if they are of that type (Warriors have a power points attribute and Magicians have a steal points attribute).
Magician Class:
public String showStats(){ // Overridden method that shows all player stats including the number of steal points.
String stats = super.showStats()+"<br>Steal Points: "+getMana()+"</html>";
return stats; }
Warrior Class:
public String showStats(){ // Overridden method that shows all player stats including the number of Power Points if they are a Warrior.
String stats = super.showStats()+"<br>Power Points: "+getMana()+"</html>";
return stats;
}
Within the class Battle I call the showStats() method and the output is not known until the User has selected what character they wish to play as. I just wanted to be certain that this is an example of polymorphism as the character selected is not known until the program has already been compiled and is then selected by the user (i.e. Substitution principle and Late Dynamic Binding).
public static void gameMenu(Player player, int choice, String name)throws FileNotFoundException, IOException, ClassNotFoundException { // Game menu method is for displaying all options (Play game, view game rules, quit) to the user when the game runs.
//Substitution principle applied to the player object depending upon what character the player wishes to select.
if (choice == 3) {
player = new Attack_Warrior();
}
else if (choice == 4) {
player = new Defensive_Warrior();
}
else if (choice == 5) {
player = new Attack_Magician();
}
else if (choice == 6) {
player = new Defensive_Magician();
}
else{
System.out.println("Error. Try again.");
play(player); // If the user enters an invalid input, the method loops and asks the player to re-enter their input.
}
Thank you very much for your time and I look forward to hearing your response, Alex