next up previous
Next: Exercise: car sales Up: Unit 08 Previous: Generalized input and output

Static method for reading

In order to construct an object according to data coming from an input channel (e.g., a text file), it is common to define a static method that reads the data from the input channel and constructs and returns an object of the class in which the method is defined.

For example, consider the class Person, where each object of the class is characterized by the information about its name and surname. Suppose that the information on the persons that we want to deal with in an application is stored in a text file that contains for each person two lines as follows:

name
surname
Then, we can define in the class Person a static method for reading the data from the file and creating a Person object as follows:

import java.io.*;

public class Person {

  private String name, surname;

  public Person (String n, String c) {
    name = n; surname = c;
  }

  public static Person read (BufferedReader br) throws IOException {
    String s = br.readLine();
    if (s == null)
      return null;
    else
      return new Person(s, br.readLine());
  }
}

Note: The static method read returns the value null if on the input channel no more data on persons is available, or an object of the class Person containing the data read from the input channel. The method can be used to read and process the data about all persons contained in a file by making use of the following loop:

BufferedReader br = ...;
Person p = Person.read(br);
while (p != null) {
   process p
   p = Person.read(br);
}


next up previous
Next: Exercise: car sales Up: Unit 08 Previous: Generalized input and output