Main Content

Objects - from physical to virtual or abstract - Java

Archive - Originally posted on "The Horse's Mouth" - 2015-02-10 17:38:43 - Graham Ellis

A train, a person, a dog, a signpost, a meal, a station ... they're all similar objects in programming terms. We can set them up in our program, save and restore attributes - and they make an excellent teaching parallel comparing real life things ("objects") of a certain type ("class").


 

 


Objects and classes can also be used for more abstract items and structures, such as file handlers, and on our courses we move on and look at the use of classes and objects in this way too. In my most recent day's training, I have used both Station objects of the original (represents something physical) and more abstarct (stream handler) types, with my main code doing no more than providing the wires that link the two.

  public static void main (String [] args) {
    MyStream RailStations = new MyStream(args[0]);
    Stations [] NationalRail = new Stations[3000];
    int stationCount = 0;
  
    String lyne;
    while ((lyne = RailStations.readLine()) != null) {
      NationalRail[stationCount++] = Stations.factory(lyne);
    }
  
    for (int k=0; k       Stations current = NationalRail[k];
      if (current.isitSmall()) {
        System.out.println(current.name + " " +
          current.getPassengers());
      }
    }
    }
  }


For true (production) code, I would have used a Vector or ArrayList object rather than hardcoding a 3000 record limit, and I would have introduced error checking and exceptions into my code, allowing for my factory to be passed poor information that didn't result in an object being returned - by these are "to follow" things at this point in the middle of the course.

Source code (both the main program and the classes) at [here].

Sample output:
  WomanWithCat:dvla5 grahamellis$ java StationStatistics railstats.xyz
  Pilning 146
  Barry Links 86
  Tees-Side Airport 14
  Hensall 184
  Breich 90
  Chapelton 190
  Achanalt 164
  Sugar Loaf 120
  Denton 30
  Acklington 192
  Elton & Orston 72
  Buckenham 100
  Havenhouse 132
  Coombe 60
  Dorking West 16
  Reddish South 56
  WomanWithCat:dvla5 grahamellis$