Polymorphism Exercise
- Create a Person class with attributes String name and int health. Create a constructor with parameter name and set health = 100;. Create getter methods for name and health and setter method for health.
- Create a Warrior class that extends Person with an attribute Weapon weapon;. Create a constructor with parameter name. Call the super constructor with the name. Create a setter method setWeapon(Weapon weapon);.
- Create a Weapon class with one abstract method strike(Warrior opponent); an no attributes.
- To the Warrior class. Add a decHealth method with a single parameter int amt. Set the health value to Math.max(0, health – amt); which will keep the health attribute from going negative. The getHealth and setHealth from Person class will be used.
- To the Warrior class add an attack method that takes a Warrior opponent parameter. If this warrior’s health is positive and the opponent’s health is positive and this warrior’s weapon is not null, print this warrior’s name is attacking the opponent’s name. Then, call the strike method of the weapon attribute of your warrior class. Finally, print the opponent’s name and health.
- Use the provided Weapons and Main classes to validate your Warrior and Weapon classes.
- Output should be:
- Xena is attacking Star
- Mesmerizing Star
- Star health = 97
- Star is attacking Xena
- Slashing Xena
- Xena health = 95
- Xena is attacking Star
- Snapping Star
- Star health = 93