Title: Computer Systems and Elements of Programming Java programming: Lecture 5
1Computer Systems
and Elements of Programming Java programming
Lecture 5
- Dr Niki Trigoni
- Department of Computer Science
- and Information Systems
- Birkbeck College, University of London
- Email niki_at_dcs.bbk.ac.uk
- Web Page http//www.dcs.bbk.ac.uk/niki
2Review of lecture 4
- Inheritance allows us to define one class as an
extension of another - A subclass is a class that extends (inherits
from) another class. It inherits all fields and
methods from its superclass. - Classes linked through inheritance relationships
form an inheritance hierarchy. - The constructor of a subclass must always invoke
the constructor of its superclass as its first
statement. If omitted, Java will attempt to
insert a constructor call automatically. - All classes with no explicit superclass have
Object as their superclass. - Subclass objects may be used wherever objects of
a superclass are expected.
3Overview of lecture 5
- Putting together arrays and inheritance
- Dynamic method lookup
- The main method and its parameters
- Reading and writing files
- String handling
4Putting together arrays and inheritance
- Say that we would like to define a class Database
with a field that contains an array of
Multimedia_Item objects - Remember that
5Putting together arrays and inheritance
public class Database // Fields private
MultiMedia_Item items private int
noOfItems // Constructor public
Database() noOfItems 0
items new MultiMedia_Item 100
What is the type of field items?
Explain where and how the field items is
initialized.
Explain where and how the field items is
initialized.
The array items will store objects of which class?
6Putting together arrays and inheritance
public class Database // Fields //
Constructor // Methods public void addItem
(MultiMedia_Item newItem) if (noOfItems
lt items.length) itemsnoOfItems
newItem noOfItems
Why did we set the type of the input parameter
to be MultiMedia_Item ?
Why do we need the if statement?
What does the method do if the array items is
full?
7Putting together arrays and inheritance
public class Database // Fields //
Constructor // Methods public void
printItems () int i for (i0
iltnoOfItems i) itemsi.print()
Why do we need a for statement to print the
field items?
- Notice in the for loop the
- Init stmt
- Continue condition
- Incrementor stmt
Can you replace the for stmt with a while stmt?
Which method do we assume that the
class MultiMedia_Item has?
8Review of method print
- Remember how we defined the following method in
class MultiMedia_Item - class MultiMedia_Item
-
- // Fields and constructor omitted
- public void print()
-
- System.out.print(Title title)
- if (gotIt)
- System.out.println()
- else
- System.out.println()
- System.out.println(Duration playingTime)
- System.out.println(Comment comment)
-
-
9Review of method overriding
- Remember how we overrode the method print in the
subclass CD? - class CD extends MultiMedia_Item
-
- // Fields and constructor omitted
- public void print()
-
- super.print()
- System.out.print (Artist artist)
- System.out.println (NoOfTracks
numberOfTracks) -
-
10Review of method overriding
- Remember how we overrode the method print in the
subclass Video? - class Video extends MultiMedia_Item
-
- // Fields and constructor omitted
- public void print()
-
- super.print()
- System.out.print (Director director)
-
-
-
11Dynamic method lookup
public class DatabaseManager public static
void main (String argv) Database db
new Database () CD item1 new CD
(Intensive Care, Robbie Williams, 12, 45)
db.addItem (item1) Video item2 new
Video (Broken Flowers, 90, Jim Jarmusch)
db.addItem (item2) db.printItems()
- Within printItems, we call the method print() on
each MultiMedia_Item object in the - items array. Which implementation of method
print() will be invoked on - the first object of the array?
- the second object of the array?
12Dynamic method lookup
- The print() method is invoked on the i-th object
as follows - The object db.itemsi is accessed.
- The most specific class of the object is found
- The class is CD for the (first) object
db.items0 - The class is Video for the (second) object
db.items1 - The implementation of the method print() of the
class (determined in the previous step) is
selected - The method print() of class CD for the first item
- The method print() of class Video for the second
item - What would happen if the method print() was not
defined in class Video? - The method print() of the immediate superclass
(Item) would be invoked.
13More complex scenario
- Suppose that we want to write a program that
- Creates a new Database object
- Reads an input text file with details about a
number of cds and videos, and adds corresponding
CD and Video objects to the field items of the
Database object - Prints the contents of items to an output text
file. - The program should have two input parameters
- The name of the input text file
- The name of the output text file
14The main method and its parameters
public class DatabaseManager public static
void main (String argv) if
(argv.length ! 2)
System.out.println (Error This program has two
arguments) System.out.println (
- inputFileName - outputFileName)
return String inputFileName
argv0 String outputFileName
argv1
15The main method (continued)
public class DatabaseManager public static
void main (String argv) // continuing
method main from previous page //
. Database db new
Database() db.readItemsFromFile
(inputFileName) db.writeItemsToFile
(outputFileName) System.out.println(Job
done!) // It remains to define two
methods of class Database // - public void
readItemsFromFile (String inputFile) // -
public void writeItemsToFile (String outputFile)
16Reading and writing files
- To read and write files, we use objects of class
- BufferedReader. For example, BufferReader has a
method (readLine) that allows us to read a line
of a given file. - FileWriter. For example, FileWriter has a method
(write) that allows us to write a string to a
given output file. - Opening, reading, writing and closing files may
cause errors (for example if we try to read a
non-existing file, or we try to write to a file
that we do not have access to). - For example, the method readLine of BufferReader
throws an exception (an object of class
Exception) if we try to read beyond the end of
file. - Wherever we use methods that can possibly throw
exceptions, we must catch potential exceptions,
i.e. write code how to react to these errors.
17Reading text from input file
try catch
(Exception e) System.out.println(Exc
eption e.toString() )
import java.io. public class Database public
void readItemsFromFile (String inputFile)
FileReader fileReader new
FileReader ( inputFile ) BufferedReader
reader new BufferedReader (fileReader) Strin
g line reader.readLine() while (line !
null) addTextLineItem (line) line
reader.readLine() reader.close()
18Writing text to output file
import java.io. public class Database public
void writeItemsToFile (String outputFile)
int i try FileWriter
writer new FileWriter ( outputFile ) for
(i0 iltnoOfItems i) writer.write(
itemsi.toString() \r\n ) writer.close()
catch (Exception e)
System.out.println(Exception e.toString() )
19Input file format
- CD - ltcd_titlegt - ltcd_artistgt -
ltcd_no_of_tracksgt - Video - ltvideo_titlegt - ltvideo_directorgt
- Example of a file with two lines
- CD-Intensive Care-Robbie Williams-12
- Video-Broken Hearts-Jim Jarmusch
20String handling
public class Database public void
addTextLineItem (String line) if
(line null) return String wordArray
line.split(-) // check the first word
to see if it is CD or Video if
(wordArray0.equals(CD)) CD cd
new CD() cd.setTitle( wordArray1) cd.set
Artist (wordArray2) Integer
noOfTracksObject new Integer (wordArray3)
cd.setNoOfTracks (noOfTracksObject.intValue())
items.addItem (cd) else
21String handling
public class Database public void
addTextLineItem (String line) //
continued from previous page // else
if (wordArray0.equals (Video))
Video video new Video() video.setTitle
(wordArray1) video.setDirector
(wordArray2) items.addItem (video)
else System.out.println (First word
of a line must be CD or Video)
22String handling
public class Item public String toString()
String str new String(Item-
getTitle()) return str
public class CD extends Item public
String toString() String str new
String(CD- getTitle()-) str.concat
(getArtist()) return str
// write similar method (toString()) for class
Video
23Summary of lecture 5
- If an array is defined to store objects of a
class C, we can store in it objects of any class
that inherits from C. - Java decides dynamically how to implement a
method invocation on an object. The
implementation selected depends on the specific
class that the object is instance of. - It is possible to pass user values to a Java
application through command-line arguments of the
main method - The classes BufferedReader, FileReader and
FileWriter can be used to read and write files. - The class String includes many methods that allow
us to handle String objects like equals, concat,
etc.
24Learning outcomes of lecture 5
- Be able to handle polymorphic arrays, i.e. arrays
that include objects of different subclasses of a
given class - Be able to explain the meaning of dynamic method
lookup and demonstrate it with the use of an
example - Be able to read and write data from files
- Be able to pass user values to a Java application
(command-line arguments of method main) - Be able to handle (compare, concatenate, etc.)
String objects using the methods of class String.