Java Reference
In-Depth Information
The output of these statements is:
e is an Employee object
e is a Serializable object
If the Employee class did not implement Serializable, the second line of the output
would not be displayed; therefore, implementing a tagging interface, although requiring no
extra work of the class, adds a data type to objects of that class.
By the way, the Serializable interface is an important tagging interface in the Java lan-
guage. A JVM can serialize an object, saving its state to a file or other output, and deserial-
ize the object at a later time. This can only be done with objects that are of type
java.io.Serializable, meaning it can only be done with objects whose class implements the
Serializable interface. This allows the designer of a class to decide whether or not the class
should be tagged as Serializable.
Interfaces and Polymorphism
If a class implements an interface, objects of the class can take on the form of
the interface data type. The capability of an object to take on the form of an
interface is an example of polymorphism. I have used this fact several times
throughout this chapter, but now I want to formally discuss the details of poly-
morphism and interfaces.
For example, in the OaklandAtDenver program discussed earlier, a Score-
Board object is passed in to a method that has a FootballListener reference. The
reason that this is valid is that the ScoreBoard class implements the Football-
Listener interface.
In fact, we could have instantiated a ScoreBoard object using a
FootballListener reference:
FootballListener scoreBoard = new ScoreBoard();
The is a relationship carries over to interfaces. ScoreBoard implements
FootballListener, so a ScoreBoard object is a FootballListener object.
Let's look at an example that demonstrates how interfaces affect polymor-
phism. We will look at a Dog class that both has a parent class and implements
an interface. The following Mammal class is the parent class.
public class Mammal
{
public void breathe()
{
System.out.println(“Mammal is breathing”);
}
}
Search WWH ::




Custom Search