Home CPSC 240

Lab 2: Encapsulation

 

Objective

To experience the difference that encapsulation makes to a program, by modifying two versions of a program — one which is encapsulated and one that is not.


 

Encapsulation

For this lab, you will work to modify two programs:

These programs do the exact same thing. They both model a simple character in a video game. The character has a health field which starts at 100 and can go down if the character is damaged, or up if the character is healed. The character also has a lives field which starts at 5. If their health goes to 0, they lose a life.

The main part of the program just tests this out by letting the user damage and heal the character as they want.

The difference is that Program1 does not use encapsulation at all. The character's fields are open to the whole program. The main method uses these directly, changing them as needed. Imagine that this program was thousands of lines in a dozen files — all of them could be changing the character's stats.

Program2 does use encapsulation. Now, the character's fields are private so they can't be changed willy nilly all over the place. They are only accessed directly in the Character class. The main method now calls into these methods to do what it has to. If this program was thousands of lines, all the logic for the character would still be in Character class.

Notice Program2 is a little longer. That is normal, but the benefits of encapsulation make it worth it.


 

Task

Imagine you were working on a big video game that used this Character class. There is then a change in the requirements that means needing to redesign how the damage is done.

Instead of having a health field, the character will have two properties. One will be the "star" property which means they take no damage at all. The other will be the "super" property which gives them one free hit.

If they are damaged when the star property is true, nothing happens. If they are damaged when the super property is true, then the super property becomes false. If they are damaged when both properties are false, they lose a life.

If they are healed when both properties are false, the super property becomes true. If they are healed when it is already true, then the star property becomes true. If they are healed when the star property is true, nothing happens.

For this to really make sense, there would have to be a way to lose the star property, but we will ignore that for now.

Your job is to change both programs to work this way instead.


 

Details


 

Submitting

When you are done, please email your two new .java files to ifinlay@umw.edu.

Copyright © 2019 Ian Finlayson | Licensed under a Creative Commons Attribution 4.0 International License.