|





| | Borrow a Monster class and MonsterControl class from someone
else in our section of java.
Use inheritance (extends) to create a new derived Monster2 class
that adds 2 new things to what the borrowed base Monster
class does (2 new methods). You may do more, if you like.
Here's how:
- CHANGE THE MONSTER PARENT CLASS
Change your instance variables from private to protected. That way,
your derived class will be able to use them. (From the perspective of
object-oriented programming, it's not "proper" to use the
protected keyword. Instead, you should write accessor functions for every
private variable you want your derived class to use. The protected
keyword is the "practical" approach. In this case, practical
means quicker and easier, so we're going to do it the practical way.)
This is the only change you need to make to the parent class.

- CREATE THE MONSTER2 CHILD CLASS
- Create a new file for the Monster2 class.
- Create the new class and use the extends keyword:

- Unfortunately, derived classes still must have their own
constructors. So, what you've got to do is create Monster2
constructors to match each constructor in the Monster class. In the
Monster2 constructors, you call the Monster constructors, using the super
keyword as follows:

As an aside, here are my Monster constructors that are called by
super:

- Now you can add new methods or override existing methods to train Monster2
to do additional things. Here's one I added:

-
CHANGE THE MONSTERCONTROLLER CLASS TO WORK WITH THE NEW MONSTER2 CHILD
CLASS
Revise the monster controller so it works with your new
derived Monster2 class instead of with the borrowed base Monster
class. First, change your declaration so it refers to Monster2:

Then, change the line where you instantiate your monster to use Monster2:
In the end, you will have 3 files:
 | The borrowed, base Monster class |
 | Your derived Monster2 class that adds new methods to
the base Monster class |
 | A revised MonsterController class.
|
Special rules:
- You are NOT allowed to change the other person's Monster
class code in any way, with one exception: You can change any or
all of the instance variables from private to protected.
- To save time, you may use the methods you created for your own
Monster class, as long as they differ in some way from what the other
person did.
Challenge: add a new static method that counts the number of
monsters created. To do this, add a counter variable to
Monster2. Revise Monster2's constructors so that, after calling
super(), they add 1 to the counter. Finally, create a static method which returns the number
of monsters created. Add a button to your monster controller to test
this method.
|