340 likes | 467 Views
File and Stream I/O, Redirection Privacy and Super. Talk About Printing. Before talking about input from keyboard, let’s first consider output to screen in Java. System.out.print() is a familiar message. System is a class. Just like Account . System has some fields, one of which is
E N D
File and Stream I/O, Redirection Privacy and Super
Talk About Printing • Before talking about input from keyboard, let’s first consider output to screen in Java. • System.out.print() is a familiar message. • System is a class. Just like Account. • System has some fields, one of which is • PrintStream out • out is an object reference to an object of class PrintStream • We further send a print() message to out
Imagine...How Might It Look Like in Java? class System { // public class fields public static PrintStream out; public static InputStream in; // private class field example private static String computerName; // private instance field example private long memoryAvailable; ... }
PrintStream InputStream PrintStream print( ) … print( ) println( ) … println( ) InputStream … … The PictureSystem.out.print() System X out in System.out is a PrintStream object reference. We then send a print() message to this object.
File and Input/Output Operations • There are classes to represent a file on disk, a file in network, or input/ output from console. • They provide methods to make file and IO operations more convenient. • Class PrintStream and Class Scanner
Class PrintStream import java.io.*; ...main(...) throws IOException { PrintStreammyNewFile; myNewFile = new PrintStream("myWeb.txt"); myNewFile.println("Hello World in a file!"); System.out.println("Hello World on screen."); // myNewFile is a PrintStream object reference // System.out is a PrintStream object reference }
PrintStream Object References PrintStream anObjectRef; anObjectRef= System.out; anObjectRef.println("Say Hello to screen!"); anObjectRef= new PrintStream("myWeb.txt"); anObjectRef.println("Say Hello to a file!"); // anObjectRef is a variable. At different time, // it refers to different PrintStream objects: // // System.out is a PrintStream object // new PrintStream() creates another object
PrintStream Object References PrintStream anObjectRef; anObjectRef = System.out; anObjectRef.println("Say Hello to screen! "); PrintStream myNewFile; myNewFile = new PrintStream("myWeb.txt"); anObjectRef = myNewFile; anObjectRef.println("Say Hello to a file! "); // we can copy object references // anObjectRef.println will print differently
Class Scanner import java.util.*; import java.io.*; ...main(...) throws Exception { Scanner markFile; markFile = new Scanner( new File("myWeb.txt") ); int mark; if (markFile.hasNextInt()) mark = markFile.nextInt(); }
Class Scanner • The methods hasNextInt(), hasNextDouble(), hasNextXyz()… return us a boolean (true/ false) value that indicates if there is more data to read from the Scanner object. • The methods nextInt(), nextDouble(), … reads a piece of data from the source for us. • Operations may fail, thus we add “throws Exception” to the main() method.
Class Scanner: line-by-line import java.util.*; import java.io.*; ...main(...) throws Exception { Scanner markFile; markFile = new Scanner( new File("myWeb.txt") ); String aLine; while (markFile.hasNextLine()) { aLine = markFile.nextLine(); System.out.println(aLine); } }
Class Scanner: line-by-line • The method nextLine() reads a line from the source for us. It returns a String. • The source for the Scanner object could be the keyboard, a file, a web source. • System.in is a field in class System. It refers to a default InputStream object, representing the keyboard.
Class Scanner • The source could be • the keyboard object • new Scanner( System.in ); • a file object • new Scanner( new File(“filename”) ); • new Scanner( new URL(“file:///...”).openStream( ) ); • a web source • new Scanner( new URL(“http://...”).openStream( ) );
System Object References • System.out is a class field. • It is an object reference of type PrintStream • It is for outputting text to the console. • System.err is a class field. • It is an object reference of type PrintStream • It is for outputting error messages to the console. • System.in is a class field. • It is an object reference of type InputStream • It is for getting key strokes from the console.
System.out Redirection • System.out.print() / println() sends text to the console screen by default. • It is possible to change this behaviour. • This is called redirection.
Redirecting System.out import java.io.*; class Redirect { public static void main(...) throws IOException { PrintStream myNewFile; myNewFile = new PrintStream("myWeb.html"); System.setOut( myNewFile ); System.out.println("Hello World Web."); // System.out refers to new PrintStream object! } }
PrintStream PrintStream PrintStream print( ) print( ) print( ) println( ) println( ) println( ) Redirect Local variable myNewFile in method main() got a new PrintStream object reference. main( ) myNewFile File [myWeb.html] Object Reference CopyingSystem.out System.out keeps the default PrintStream object reference. Console Screen System X out in
PrintStream PrintStream PrintStream print( ) print( ) print( ) println( ) println( ) println( ) Redirect main( ) myNewFile Object Reference CopyingSystem.out Console Screen System X out in Message System.setOut(myNewFile) changes the field System.out by object reference copying! File [myWeb.html]
System Object References • System.setOut(someObj) is a class method. • It takes an object reference of type PrintStream • It is for redirecting System.out to the given object. • System.setErr(someObj) is a class method. • It takes an object reference of type PrintStream • It is for redirecting System.err to the given object. • System.setIn(someObj) is a class method. • It takes an object reference of type InputStream • It is for redirecting System.in to the given object.
Significance • We can redirect the print out beforeexecutingan existing class/ object/ program like this: import java.io.*; class Redirector { public static void main(String[] args) throws IOException { PrintStream f = new PrintStream("out.txt"); System.setOut(f); TargetClass.main(args); } }
Redirector in Action Redirector main( args ) - Create new PrintStream object [f] - Redirect System.out to [f] - Send message to main() method of TargetClass (pass parameter args as is) TargetClass main( args ) System.out.println("Hello"); would go to [f]
Extras • Under Command Prompt/ Shell, standard input/ output re-direction is also available in command line: • e.g. dir > filelist.txt myprog.exe > output.txt myprog.exe < input.txt myprog.exe < input.txt > output.txt
Soul of Object Oriented Programming • Encapsulation • Protecting Data and Method: Class and Object Access Control • Modularity • Structured Class and Method: Divide-and-Conquer • Inheritance • Extends Mechanism: Reuse-and-Build Related Classes • Polymorphism • Dynamic Type Binding: Type-Oriented Method Invocation
What’re Inherited Exactly? public/protected static/instance fields/methods Octopus OctopusWatch public useValue() addValue() protected value private cardDimension public useValue() addValue() protected value
What’re NOT Inherited? private static/instance fields/methods • Although they are not inherited, we may re-declare them in the subclass. • However, the context is not the same as the superclass.
What’s More? • Modifiers public, private and protectedDO NOT ONLY dictate what would be inherited. • Remember that they ALSO affect the scope of a member.
Privacy • Member (field/method) modifiers revisited: • public: a member is accessible anywhere • private: a member is ONLY accessible by that class • protected: a member is ONLY accessible by that class AND the subclasses of that class.
Protected Member class Account { // class field public static double minBalance = 100.00; // instance field protected double balance; ... } class CurrentAccount extends Account {...} • balance is a protected member of the class Account. • CurrentAccount is a subclass of Account, thus it can inherit and access balance too!
Graphically Octopus OctopusWatch Valid Access public useValue() addValue() protected value private cardDimension public useValue() addValue() protected value timerMethod() time Invalid Access OtherClass someMethod()
Super Construction • Constructors revisited: • On creating a new object, a constructor of the corresponding class will be invoked to initialize the object. • Subclass may have its own constructors. • Shall such constructors be responsible for doing the initialization performed by the constructors of the superclass?
class Account { // class field public static double minBalance = 100.00; // instance field protected double balance; // constructor method public Account(double initialBalance) { balance = initialBalance; } // instance method public void deposit(double amount) { balance += amount; } public void withdraw(double amount) { balance -= amount; } } class CurrentAccount extends Account { // instance field private int noChequesIssued; // constructor method public CurrentAccount(double initialBalance) { super(initialBalance); noChequesIssued = 0; } // instance method public void issueCheque() { noChequesIssued++; System.out.println(noChequesIssued + " cheques issued so far."); System.out.println("Balance: " + balance); } // main method public static void main(String[] args) { CurrentAccount michaelCheque; michaelCheque = new CurrentAccount(100); michaelCheque.deposit(200); michaelCheque.issueCheque(); } } Responsible for initializing the field noChequesIssued Example Responsible for initializing the field balance
class Account { // class field public static double minBalance = 100.00; // instance field protected double balance; // constructor method public Account(double initialBalance) { balance = initialBalance; } // instance method public void deposit(double amount) { balance += amount; } public void withdraw(double amount) { balance -= amount; } } class CurrentAccount extends Account { // instance field private int noChequesIssued; // constructor method public CurrentAccount(double initialBalance) { super(initialBalance); noChequesIssued = 0; } // instance method public void issueCheque() { noChequesIssued++; System.out.println(noChequesIssued + " cheques issued so far."); System.out.println("Balance: " + balance); } // main method public static void main(String[] args) { CurrentAccount michaelCheque; michaelCheque = new CurrentAccount(100); michaelCheque.deposit(200); michaelCheque.issueCheque(); } } On creating a new CurrentAccount object, this constructor will be called Example On creating a new Account object, this constructor will be called
class Account { // class field public static double minBalance = 100.00; // instance field protected double balance; // constructor method public Account(double initialBalance) { balance = initialBalance; } // instance method public void deposit(double amount) { balance += amount; } public void withdraw(double amount) { balance -= amount; } } class CurrentAccount extends Account { // instance field private int noChequesIssued; // constructor method public CurrentAccount(double initialBalance) { super(initialBalance); noChequesIssued = 0; } // instance method public void issueCheque() { noChequesIssued++; System.out.println(noChequesIssued + " cheques issued so far."); System.out.println("Balance: " + balance); } // main method public static void main(String[] args) { CurrentAccount michaelCheque; michaelCheque = new CurrentAccount(100); michaelCheque.deposit(200); michaelCheque.issueCheque(); } } On creating a new CurrentAccount object, this constructor will be called Example Remember that the field balance is inherited in CurrentAccount objects.
class Account { // class field public static double minBalance = 100.00; // instance field protected double balance; // constructor method public Account(double initialBalance) { balance = initialBalance; } // instance method public void deposit(double amount) { balance += amount; } public void withdraw(double amount) { balance -= amount; } } class CurrentAccount extends Account { // instance field private int noChequesIssued; // constructor method public CurrentAccount(double initialBalance) { super(initialBalance); noChequesIssued = 0; } // instance method public void issueCheque() { noChequesIssued++; System.out.println(noChequesIssued + " cheques issued so far."); System.out.println("Balance: " + balance); } // main method public static void main(String[] args) { CurrentAccount michaelCheque; michaelCheque = new CurrentAccount(100); michaelCheque.deposit(200); michaelCheque.issueCheque(); } } On creating a new CurrentAccount object, this constructor will be called Example We thus have to call the constructor of the superclass (Account) to perform suitable initializations