Information Hiding and Reusing Classes
Exercises
- Create a package package1. Don't forget to insert your package into a directory
of the same name. Insert a class AccessTest into this packge.
Define public, friendly and private data members and methods in your class AccessTest.
Define a second class Accessor1 in your package that accesses the
different kinds of data members of methods (private, public, friendly). See what compiler
messages you get.
- Define class Accessor2 outside the package. Again try to access all
methods and data members of the class AccessTest. See what compiler
messages you get. Where are the differences between Accessor1 and Accessor2
?
- Define a Class Building for building objects. Each building has a door
as one of its components.
- In the class Door, model the fact that a door has a color and three
states, "open" , "closed", and "locked". To avoid illegal
state changes, make the state private, write a method (getState) that inspects the
state and four methods (open, close, lock and unlock) that change the state. Initialize
the state to "closed" in the constructor. Look for an alternative place for this
initialization.
- Write a method enter that visualizes the process of entering the
building (unlock door, open door, enter, ...) by printing adequate messages, e.g. to show
the state of the door.
- Write a corresponding method quit that visualizes the process of
leaving the house. Don't forget to close and lock the door.
- Test your class by defining an object of type Building and visualizing
the state changes when entering and leaving the building.
- Extend exercise 3 by introducing a subclass HighBuilding that contains
an elevator and the height of the building in addition to the components of Building.
Override the method enter to reflect the use of the elevator. Define a
constructor that takes the height of the building as a parameter.
- Define a subclass Skyscraper of HighBuilding,
where the number of floors is stored with each skyscraper. What happens, if you
don't define a constructor for class Skyscraper (Try it)? Write a constructor that takes
the number of floors and the height as a parameter. Test the class by creating a
skyscraper with 40 floors and using the inherited method enter.
For exercises 4 and 5 you need inheritance syntax, that we did not cover in the lecture
yet. If you want to start with this exercises before the next lecture look into the slides
or ask the advisors.

|
|
Claudia Niederée, nov 1998 |