Problem Derivation

   

Java™ 2 Primer Plus
By Steven Haines, Steve Potts

Table of Contents
Chapter 12.  Using Java's Input and Output Classes


If you have ever had to deal with gathering data from a file, from the Internet, and from the user, you had to write three different mechanisms to obtain this data. Traditionally, each input and output device had its own proprietary interface. This was necessary because although the underlying data might be the same, one is loaded from tracks on a physical disc, one is loaded by opening a socket connection to a server, and the other is read from a keyboard. Different devices meant that the mechanism to obtain the data had to be different.

What can be done in an environment that promotes hardware independence? Can that notion be extrapolated to include different input and output devices? With Java's support for interfaces, the answer is, yes we can.

Consider the nature of interfaces: A class that implements an interface provides prescribed functionality that is made available through a set of methods, but the underlying implementation is irrelevant. We can, therefore, create an interface called Input and an interface called Output, and define classes that implement these that access different devices:

 public interface Input {    public Stuff readStuff();  }  public interface Output {    public void writeStuff( Stuff s );  }  public class FileInput implements Input {    public Stuff readStuff() {      return getStuffFromFile();    }  }  public class KeyboardInput implements Input {    public Stuff readStuff() {      return getStuffFromKeyboard();    }  }  public class InternetInput implements Input {    public Stuff readStuff() {      return getStuffFromInternet();    }  } 

These classes are obviously written in a Java pseudo-code, but the notion is apparent: each class provides a unique implementation for a common set of functionality. When a new requirement arises that asks for data read from a dial-up proprietary connection (such as a Value Added Network (VAN)), then a new VANInput class can be created that implements the Input interface. Now all the code that can read a file can also read the data from a VAN.

The versatility of interfaces and interface-based programming allows for this to succeed. The concept is that code is written against an interface instead of a class so that you are free at any time to change the underlying implementation.


       
    Top
     



    Java 2 Primer Plus
    Java 2 Primer Plus
    ISBN: 0672324156
    EAN: 2147483647
    Year: 2001
    Pages: 332

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net