Starting from:
$30

$24

Homework 3 Solution

We will expand our Warrior a little. Each Warrior will have a weapon. He is "born" with it, i.e. the weapon is created together with the warrior. It can only be accessed by him. It provides him with his strength. In battle, weapons lose their edge and weaken. When a Warrior's weapon loses all of its strength, the Warrior himself dies.




Implementation

Remember that we are using data hiding. Therefore, every field, aka member variable, must be private.




What are the types of things in the problem? We will need a class for each type.




What do the things / types do? These "behaviors" should be represented as methods.




Weapons have both a name and a strength. The weapon is created together with the Warrior and cannot be accessed by anyone else.




Note that the input file changed a little, compared to the previous assignment. When a Warrior is created, instead of simply specifying his name and strength, the Warrior command specifies the Warrior's name as well as his Weapon's name and its strength.




The Status report will is also modified to show the name of the Warrior's Weapon.




No one can access a warrior's weapon except the warrior himself. But the weapon is what actually holds the warrior's strength. How does this effect the programming? Any time the code needs to know or change the warrior's strength, the warrior then "asks" the weapon what the strength is or tells the weapon that the strength needs to be changed. This represents the idea of delegation. We will see this concept frequently, where one object requests that another object do some task.




It is in fact unnecessary for any code other than a Warrior to even know about the Weapon. We will enforce this by nesting the definition of the Weapon class inside the Warrior class. To make sure that no code other than Warrior's makes use of Weapon, we need to make the class private.




One last implementation detail. to display the information about an object, whether it is a warrior or a weapon, we will use that object's output operator.

More products