Java Reference
In-Depth Information
Using
Object
as a Parameter
If you need to write a method that takes in any type of argument, use
Object
as the data
type of the parameter. This situation is quite common in the Java API. For example, the
writeObject
method of
ObjectOutputStream
takes in an
Object
:
public final void writeObject(Object obj)
Because of polymorphism, every object in Java is of type
Object
. Therefore, any
reference can be passed into the
writeObject
method. Of course, as we saw in
Chapter 4, “API Contents,” the
Object
passed in to
writeObject
needs to be of type
Serializable
or an exception is thrown. The
writeObject
method uses the
instanceof
operator to determine if the argument passed in implements
Serializable
. The code
looks similar to the following:
if(!(obj instanceof Serializable)) {
throw new NotSerializableException(obj.getClass());
}
Using Polymorphic Parameters
I developed an application that required an event to be logged every time a customer
preference is changed. For example, a customer can choose whether or not to receive
emails with promotions, special offers, and news items, and these preferences are stored
in a database. The corresponding Java objects to represent the various preferences all
extend a class named
Preference
. The event logging method is defi ned as
public void preferenceChanged(Preference pref) {
logger.writeUTF(pref.toString());
}
The
logger
variable is a
DataOutputStream
that writes to a fi le. Instead of defi ning
multiple overloaded
preferenceChanged
methods, this single method can log
any
Preference
that is changed. If a new type of preference comes along, the
preferenceChanged
method can remain unchanged as long as the new preference
extends the
Preference
class.
Search WWH ::
Custom Search