Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^356) | Inheritance, Polymorphism, and Scope
publicString full()
publicString lastFirstMI()
// Additional observer methods that compare an instance to another name
public booleanequals(Name otherName)
public intcompareTo(Name otherName)
}
In Chapter 8 we explain the meaning of the implementsclause in the class heading. For
our purposes here it is sufficient to view it as a way of telling Java that objects of this class
can be output and input using writeObjectand readObject, respectively.
Our first application reads the data for the three fields from a file, instantiates a Nameob-
ject, and then writes the Nameobject onto the second file. The second application reads the
Nameobject and prints it.
importjava.io.*;
importName;
public classObjectFileWrite
{
public static voidmain(String[] args) throwsIOException
{
ObjectOutputStream outObject; // Output data file
BufferedReader inFile; // Input data file
String first;
String second;
String last;
Name person;
// Prepare files
inFile = new BufferedReader(new FileReader("infile.dat"));
outObject =
new ObjectOutputStream(new FileOutputStream("outObject.dat"));
// Read names from the file
first = new String(inFile.readLine());
second = new String(inFile.readLine());
last = new String(inFile.readLine());
// Instantiate a person
person = new Name(first, last, second);
// Write out person
outObject.writeObject(person);
// Close files and quit
outObject.close();
inFile.close();
}
}

Free download pdf