Copyright by Michael P.F. Fung
2
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
Copyright by Michael P.F. Fung
3
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;
...
}
Copyright by Michael P.F. Fung
4
The PictureSystem.out.print()
SystemSystem
out
in
PrintStreamPrintStream
print( )
println( )
PrintStreamPrintStream
print( )
println( )InputStreamInputStream
…
…
InputStreamInputStream
…
…
System.out is a PrintStream object reference.
We then send a print() message to this object.
Copyright by Michael P.F. Fung
5
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
Copyright by Michael P.F. Fung
6
Class PrintStreamimport java.io.*;
...main(...) throws IOException{ PrintStream myNewFile;
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}
Copyright by Michael P.F. Fung
7
PrintStream Object ReferencesPrintStream 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
Copyright by Michael P.F. Fung
8
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
Copyright by Michael P.F. Fung
9
Class Scannerimport 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();
}
Copyright by Michael P.F. Fung
10
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.
Copyright by Michael P.F. Fung
11
Class Scanner: line-by-lineimport 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); }}
Copyright by Michael P.F. Fung
12
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.
Copyright by Michael P.F. Fung
13
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( ) );
Copyright by Michael P.F. Fung
14
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.
Copyright by Michael P.F. Fung
15
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.
Copyright by Michael P.F. Fung
16
Redirecting System.outimport 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! }}
Copyright by Michael P.F. Fung
17
Object Reference CopyingSystem.out
SystemSystem
out
in
PrintStreamPrintStream
print( )
println( )
PrintStreamPrintStream
print( )
println( )
System.out keeps the default PrintStream object reference.
Console Screen
PrintStreamPrintStream
print( )
println( )
RedirectRedirect
main( )
myNewFileLocal variable myNewFile in method main() got a new PrintStream object reference.
File [myWeb.html]
Copyright by Michael P.F. Fung
18
Object Reference CopyingSystem.out
SystemSystem
out
in
PrintStreamPrintStream
print( )
println( )
PrintStreamPrintStream
print( )
println( )Message System.setOut(myNewFile) changes the field System.out by object reference copying! PrintStreamPrintStream
print( )
println( )
RedirectRedirect
main( )
myNewFile
Console Screen
File [myWeb.html]
Copyright by Michael P.F. Fung
19
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.
Copyright by Michael P.F. Fung
20
Significance• We can redirect the print out before executing
an 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); }}
Copyright by Michael P.F. Fung
21
Redirector in Action
RedirectorRedirector
main( args )
- Create new PrintStream object [f]- Redirect System.out to [f]- Send message to main() method of TargetClass(pass parameter args as is) TargetClassTargetClass
main( args )
System.out.println("Hello");
would go to [f]
Copyright by Michael P.F. Fung
22
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
Copyright by Michael P.F. Fung
24
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
Copyright by Michael P.F. Fung
25
What’re Inherited Exactly?
public/protected static/instance fields/methods
public
useValue()
addValue()
protected
value
private
cardDimension
public
useValue()
addValue()
protected
value
private
cardDimension
public
useValue()
addValue()
protected
value
public
useValue()
addValue()
protected
value
OctopusWatch
Octopus
Copyright by Michael P.F. Fung
26
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.
Copyright by Michael P.F. Fung
27
What’s More?
• Modifiers public, private and
protected DO NOT ONLY dictate what
would be inherited.
• Remember that they ALSO affect the
scope of a member.
Copyright by Michael P.F. Fung
28
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.
Copyright by Michael P.F. Fung
29
Protected Memberclass 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!
Copyright by Michael P.F. Fung
30
Graphically
public
useValue()
addValue()
protected
value
private
cardDimension
public
useValue()
addValue()
protected
value
private
cardDimension
public
useValue()
addValue()
protected
value
timerMethod()
time
public
useValue()
addValue()
protected
value
timerMethod()
time
OctopusWatch
Octopus
someMethod()someMethod()
OtherClass
Invalid Access
Valid Access
Copyright by Michael P.F. Fung
31
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?
Copyright by Michael P.F. Fung
32
Exampleclass 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
Responsible for initializing the field balance
Copyright by Michael P.F. Fung
33
Exampleclass 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 Account object, this
constructor will be called
On creating a new CurrentAccount object, this constr
uctor will be called
Copyright by Michael P.F. Fung
34
Exampleclass 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(); }}
Remember that the field balance is inherited in Curr
entAccount objects.
On creating a new CurrentAccount object, this constr
uctor will be called
Copyright by Michael P.F. Fung
35
Exampleclass 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 constr
uctor will be called
We thus have to call the constructor of the superclass (Account) to perfor
m suitable initializations