Java Reference
In-Depth Information
Tagging Interfaces (continued)
java.io.Serializable is an example of a tagging interface that is not designed to be a par-
ent interface, but instead is meant to be implemented by a class so that objects of the class
become Serializable objects. The Serializable interface is defined as:
package java.io;
public interface Serializable
{
public static final long serialVersionUID;
}
Notice Serializable has one field, but no methods. A class can implement Serializable
simply by declaring implements Serializable , and no additional changes are required of the
class. The following Employee class implements the Serializable interface.
public class Employee implements java.io.Serializable
{
public String name, address;
public double weeklyPay;
public void computePay(int hoursWorked)
{
weeklyPay = hoursWorked * 6.50;
System.out.println(“Weekly pay for “ + name
+ “ is $” + weeklyPay);
}
public void mailCheck()
{
System.out.println(“Mailing check to “ + name
+ “ at “ + address);
}
}
Why implement an interface with no methods in it? What is different about the
Employee class now that it implements Serializable? Well, the answer is based on poly-
morphism. If a class implements an interface, objects of the class can be treated as the
interface data type. For example, an Employee object can be treated as a Serializable
object.
Consider the following statements that use this Employee class. What is the output?
Employee e = new Employee();
if(e instanceof Employee)
{
System.out.println(“e is an Employee object”);
}
if(e instanceof java.io.Serializable)
{
System.out.println(“e is a Serializable object”);
}
Search WWH ::




Custom Search