Java Reference
In-Depth Information
Self-Test Exercises
(continued)
public int
getStuff()
{
return
intStuff;
}
public
String getStuff(String someStuff)
{
return
someStuff;
}
}
The
Serializable
Interface
★
As we have already noted, the designers of Java often used the interface mechanism
to take care of miscellaneous details that do not really fit the spirit of what an inter-
face is supposed to be. An extreme example of this is the
Serializable
interface.
The
Serializable
interface has no method headings and no defined constants. As a
traditional interface it is pointless. However, Java uses it as a type tag that means the
programmer gives permission to the system to implement file I/O in a particular
way. If you want to know what that way of implementing file I/O is, see Chapter 10,
in which the
Serializable
interface is discussed in detail.
Serializable
The
Cloneable
Interface
The
Cloneable
interface is another example where Java uses the interface mechanism
for something other than its traditional role. The
Cloneable
interface has no method
headings that must be implemented (and has no defined constants). However, it is
used to say something about how the method
clone
, which is inherited from the class
Object
, should be used and how it should be redefined.
So, what is the purpose of the
Cloneable
interface? When you define a class to
implement the
Cloneable
interface, you are agreeing to redefine the
clone
method
(inherited from
Object
) in a particular way. The primary motivation for this appears
to be security issues. Cloning can potentially copy private data if not done correctly.
Also, some software may depend on your redefining the
clone
method in a certain
way. Programmers have strong and differing views on how to handle cloning and the
Cloneable
interface. What follows is the official Java line on how to do it.
The method
Object.clone()
does a bit-by-bit copy of the object's data in storage.
If the data is all primitive type data or data of immutable class types, such as
String
,
then this works fine and has no unintended side effects. However, if the data in the
object includes instance variables whose type is a mutable class, then this would cause
what we refer to as
privacy leaks.
(See the Pitfall section entitled “Privacy Leaks” in
Chapter 5.) To avoid these privacy leaks when you define the
clone
method in a
Cloneable