Vous êtes sur la page 1sur 7

95712C Lecture Notes

Wednesday, September 29, 2004


1. StringTokenizer Class
Reference: Chapter 12 of Core Java
The StringTokenizer class helps to break the sentences into individual words, which are
called tokens The tokens are separated b! deli"eters, usuall! the white space characters
The StringTokenizer class is defined in the #avautil package
public StringTokenizer$String str%
public StringTokenizer$String str, String deli"%
Constructs a string tokenizer for the specified string The characters in the deli"
argu"ent are the deli"iters for separating tokens
public StringTokenizer$String str, String deli", boolean returnTokens%
&f the returnTokens flag is true, then the deli"iter characters are also returned as
tokens
boolean has'oreTokens$% returns true if "ore tokens e(ist
String ne(tToken$% returns the ne(t token
See the e(a"ple in the ne(t section
2. Introduction to Files and Input/Output
Reference: Chapter 12 of Core Java
)e will stud! the files and Java &*+ later ,et us see briefl! how to read fro" and write to
&*+ strea"s
See the e(a"ple below for reading fro" a file through buffered strea"
import java.io.*;
import java.util.StringTokenizer;
public class Demonstrate {
public static void main(String argv[]) throws IOException {
BufferedReader instream = new BufferedReader( new
FileReader("input.data"));
PrintWriter outstream = new PrintWriter( new
FileWriter("output.data"));

String line;
while ( (line = instream.readLine()) != null) {
StringTokenizer tokenizer = new StringTokenizer(line);
int sum = 0;
while (tokenizer.hasMoreTokens()) {
sum += Integer.parseInt(tokenizer.nextToken());
}
outstream.println("The sum is: " + sum);
}
instream.close();
outstream.close();
}
}
)hile reading or writing the -ile strea"s, an e(ception "a! occur such as input file not
found or per"ission denied writing on output file &n such situations, Java throws an &*+
e(ception such as -ile.ot-ound/(ception -or the ti"e being, we will not deal with the
e(ception: )e will si"pl! declare that a "ethod can throw a particular e(ception and we
will not write an! code to catch that e(ception
Three strea" ob#ects created auto"aticall!: S!ste"in which is the strea" that flows
fro" the ke!board to the progra", S!ste"out which is the strea" that flows fro"
progra" to displa! unit, and S!ste"err that enables the progra" to output error
"essages to the displa! unit
0e!board 12 S!ste"in 12 3rogra" 12 S!ste"out 12 4ispla!
To read fro" the ke!board, S!ste"inread reads a single character fro" the standard
input To read the input as tokens, create an &nputStrea"Reader ob#ect
import java.io.*;
import java.util.StringTokenizer;
public class Demonstrate {
public static void main(String argv[]) throws IOException {
BufferedReader in = new BufferedReader( new InputStreamReader(System.in));
String line;
while ( (line = in.readLine()) != null) {
StringTokenizer tokenizer = new StringTokenizer(line);
while (tokenizer.hasMoreTokens()) {
System.out.println(tokenizer.nextToken());
}
}
}
}
See 4ata-ileTest#ava
3. Inheritance and Polyorphis! Continued
Reference: Chapter 5 of Core Java, Chapter 6 of Thinking &n Java
3.1. Pure Inheritance vs Extension (Substitution
Principle)
&n pure inheritance, the base class establishes the interface for the whole inheritance
hierarch! Subclasses override the i"ple"entation without adding new "ethods
This can be thought of as pure substitution, because derived class ob#ects can be perfectl!
substituted for the base class, and !ou never need to know an! e(tra infor"ation about
the subclasses when !ou7re using the":
8 new t!pe of shape can be introduced into the inheritance hierarch! without changing
the code in the 9Talks to Shape: bo( /ver!thing is handled through pol!"orphis"
+n the other hand, often the sub classes have other features that re;uire additional
"ethods to i"ple"ent:
)hile this is also a useful and sensible approach $depending on the situation%, it has a
drawback The e(tended part of the interface in the derived class is not available fro" the
base class, so !ou can7t call the new "ethods:
<ou7ll get into a situation in which !ou need to rediscover the e(act t!pe of the ob#ect so
!ou can access the e(tended "ethods of that t!pe, which is studied ne(t
3.2. Casting
8n ob#ect reference of t!pe super class can refer to an! ob#ect of sub classes The
reverse is not true, !ou need an e(plicit cast in order to co"pile
<ou can cast within an inheritance hierarch! Tr! to "ini"ize the casting as possible
=se instanceof operator before casting a super class ob#ect to a sub class one
class Employee {
}
class Manager extends Employee {
}
class Engineer extends Employee {
}
public class CastingDemonstrate {
public static void main(String argv[]) {
Employee e = new Employee();
Manager m = new Manager();
Engineer en = new Engineer();
e = m; // OK
//m = e; // compile error
e = new Manager();
// m = e; // again, compile error.
m = (Manager)e;
e = new Engineer();
// m = (Manager)e; // run time cast exception.
if (e instanceof Manager) {
m = (Manager)e;
}
}
}
3.3. Order o Constructor Calls
See the Sandwich#ava as an e(a"ple of how the default constructors are invoked )hen
writing non1default constructors, "ake sure to call the super constructor in order to
achieve the correct se;uence of constructor calls
3.!. "ene#ts o Pol$%orphis%
>eneric 3rogra""ing: 3ol!"orphis" enables !ou to use #ust one t!pe and an!
subclass is taken care of
4!na"ic ?inding: Correct i"ple"entation $right behavior% is obtained via the actual
t!pe
/(tensibilit!: 8 new class can be added into the hierarch! without changing the
generic code
3.&. 'bstract Classes
8n abstract class has no instances .o instance of an abstract class can be created as the!
are considered too generic @owever, we can have references to abstract classes
8n abstract class "a! contain abstract methods, that is, "ethods with no i"ple"entation
&n this case, the subclasses "ust i"ple"ent the abstract "ethods &n this respect, abstract
classes establish an interface
8bstract classes usuall! hold instance variables and setter and getter "ethods for the
instance variables
8n e(a"ple abstract class is the Number class in the java.lang package represents the
abstract concept of nu"bers &t "akes sense to "odel nu"bers in a progra", but it
doesnAt "ake sense to create a generic nu"ber ob#ect &nstead, the Number class "akes
sense onl! as a super class to classes like Integer and Float, both of which i"ple"ent
specific kinds of nu"bers
abstract class .u"ber B

C
See 3ersonTest#ava
The following e(a"ple creates a hierarch! for a pa!roll s!ste" $adapted fro" 4eitels D
Java @ow To 3rogra"% See 8bstract/"plo!ee#ava
3.(. )he Ob*ect Class
See /;ualsTest#ava regarding the e;uals, toString and getClass "ethods
3.+. Overriding private %ethods ,
3rivate "ethods are final &f !ou define a "ethod in a subclass with the sa"e signature of
a private "ethod in super class, !ou are actuall! defining a new "ethod in the sub class
4on7t
class E {
private void f() {
System.out.println("E");
}
public void g() {
f();
}
}
public class D extends E {
private void f() {
System.out.println("D");
}
public void g() {
f();
}
public static void main(String[] args) {
E e = new E();
e.g();
D d = new D();
d.g();
}
}
)hat if class 4 doesn7t define g$% at allE
3.-. Overloading an inherited %ethod
&t is possible but don7t
class E {
private void f() {
System.out.println("E");
}
public void g() {
f();
}
}
public class D extends E {
private void f() {
System.out.println("D");
}
public void g() {
f();
}
public void g(int i) {
f();
}
public static void main(String[] args) {
E e = new E();
D d = new D();
d.g();
d.g(1);
}
}
)hat if class 4 doesn7t define g$% at allE
3... "ehavior o pol$%orphic %ethods inside
constructors
class E {
private void f() {
System.out.println("E");
}
E() {
g();
}
public void g() {
f();
}
}
public class D extends E {
private void f() {
System.out.println("D " + i);
}
public void g() {
f();
}
D() {
i = 10;
g();
}
private int i;
public static void main(String[] args) {
D d = new D();
}
}
This is different fro" CFF &nside Java constructors, eli"inate calls to "ethods that can
be overridden
". #rray$ist re%isited
See 8rra!,istTest#ava
&. 'e(lection
See ReflectionTest#ava
See +b#ect8nal!zerTest#ava
See 8rra!>rowTest#ava

Vous aimerez peut-être aussi