Java Reference
In-Depth Information
Coming back to our CowboyHat class, you might want to have operations that you could refer to as
putHatOn and takeHatOff, which would have meanings that are fairly obvious from their names,
and do make sense for CowboyHat objects. However, these operations would only be effective if a
CowboyHat object also had another defining value that recorded whether it was on or off. Then these
operations on a particular CowboyHat object could set this value for the object. To determine whether
your CowboyHat was on or off, you would just need to look at this value. Conceivably you might also
have an operation changeOwner by which you could set the instance variable recording the current
owner's name to a new value. The illustration shows two operations applied in succession to a
CowboyHat object.
owner: JonF
type: Stetson
color: White
size: 7
hatOn: true
owner: TimB
type: Stetson
color: White
size: 7
hatOn: false
owner: JonF
type: Stetson
color: White
size: 7
hatOn: false
Of course, you can have any operation for each type of object that makes sense for you. If you want to
have a shootHoleIn operation for Hat objects, that's no problem. You just have to define what that
operation does to an object.
You are probably wondering at this point how an operation for a class is defined. As we shall see in
detail a bit later, it boils down to a self-contained block of program code called a method that is
identified by the name you give to it. You can pass data items - which can be integers, floating point
numbers, character strings or class objects - to a method, and these will be processed by the code in the
method. A method may also return a data item as a result. Performing an operation on an object
amounts to 'executing' the method that defines that operation for the object.
Of course, the only operations you can perform on an instance of a particular class are
those defined within the class, so the usefulness and flexibility of a class is going to
depend on the thought that you give to its definition. We will be looking into these
considerations more in Chapter 5.
Search WWH ::




Custom Search