Copyright 2000 Kasper B. Graversen 2
Staying on the right trackStaying on the right track
• Understand and use loops
• Understand and use branching (if-else)
• Typecast between simple types
• Understand the problems of mixing types in calculations
• Know what Javadoc is and how its used
Copyright 2000 Kasper B. Graversen 3
Questions/commentsQuestions/commentsHomework assignment• So how was it?
Lab exercise• Why so difficult?• Compared to HA?• StatisticsQuestions for today’s chapter• Is the chapter easier than the earlier ones?
Copyright 2000 Kasper B. Graversen 4
Questions/commentsQuestions/comments
Lab exercises – lessons learned– Nothing is done automatically.
– The computer has no understanding of hours and minutes
– It is tough to program when in doubt of operators, language constructs (+=, “Void” vs. “void”)
Copyright 2000 Kasper B. Graversen 5
Course dictionaryCourse dictionary
• TypecastingTypecastingConverting from one type to another, ie from Converting from one type to another, ie from double to intdouble to int
• Bits/BytesBits/BytesBits is the smallest representation in a computer, Bits is the smallest representation in a computer, typically represented by voltage or no-voltage. 8 typically represented by voltage or no-voltage. 8 bits goes to 1 byte, 1024 bytes goes to 1 Kilobyte, bits goes to 1 byte, 1024 bytes goes to 1 Kilobyte, 1024 KB goes to one Megabyte… 1024 KB goes to one Megabyte…
Copyright 2000 Kasper B. Graversen 6
Today’s programToday’s program
• Class repetition
• Nested method calling
• Streams in/out• Exceptions
• Access modifiers - easy reuse of software
• JG’s packages
• File handling
Copyright 2000 Kasper B. Graversen 7
A basic Java classA basic Java class
class ClassName {
type1 attributename1;
type2 attributename2;
className(type3 attributename3,…) { … }
returntype methodName(…) { … }}
Several can exist
Several can exist
Copyright 2000 Kasper B. Graversen 8
Class buildingClass building
• What is the class definition?– Abstract definition of a thing, (horse, time)
• What is a constructor?– The mechanical steps needed to initialize an object
correctly
– Should not perform any other actions (JG go home!)
• What does methods operate on?– An instantiated object (addTime())
Copyright 2000 Kasper B. Graversen 9
Curios Curios (found on page 21)(found on page 21)
class Curio
{
String name;
int price;
String description;
Curio(String n, int p, String d)
{
name = n;
price = p;
description = d;
}
void write()
{
System.out.println(name + " " + description + " for G" + price);
}
}
Copyright 2000 Kasper B. Graversen 10
The CurioStore programThe CurioStore programclass CurioStore1
{
Curio mugs, tshirts, carvings;
CurioStore1()
{
mugs = new Curio("Traditional mugs", 6, "beaded in Ndebele style");
tshirts = new Curio("T-shirts", 30, "sizes M to XL");
carvings = new Curio("Masks", 80, "carved in wood");
System.out.println("The Polelo Curio Store sells\n");
mugs.write();
tshirts.write();
carvings.write();
}
public static void main(String[] args)
{
new CurioStore1 ();
}
}
Copyright 2000 Kasper B. Graversen 11
How is this to be drawn?How is this to be drawn?
CurioStore1
Curio mugsCurio tshirtsCurio carvings
Curiowrite()name = T-shirtsprice= 30description= sizes M to…
Curiowrite()name = traditional mugsprice= 6description= beaded in…
Curiowrite()name = Masksprice= 80description= carved in …
System
PrintStream out
PrintStreamprint(String s)println(String s)
System.out.println("The Polelo Curio Store sells\n");tshirts.write();
s.o.p(“name + " " + description+…);
Copyright 2000 Kasper B. Graversen 12
Nested method callsNested method calls
• How do we find the biggest integer a,b,c– int abmax = Math.max(a,b);– int abcmax = Math.max(abmax,c);
• The signature of max()is– int max(int x, int y)– The result of calling max()is an int– max(max(a,b), c)– in java-> Math.max(Math.max(a,b), c);
Copyright 2000 Kasper B. Graversen 13
ScopeScope• The {} encompasses code in a scope
class Foo{ int var; void foobar() { … }
int bar(int foo) { … for(…) { … } }}
Copyright 2000 Kasper B. Graversen 14
State and programmingState and programming• Procedural programs work by state-change.
• The state of a program: variables (mutable typed containers)
position (place in code where executing)
external files (input/output file positions)
• The program comprises: declarations - (description of variables: names and types)
statements - (list of operations to be performed)
• State is dynamic; program is static. by Andrew
Taylor
Copyright 2000 Kasper B. Graversen 15
Types of programsTypes of programs• A look back at “slides 1”
• Learn the basics of programming-> “DOS programs” – Programs with no interaction
– Programs with interaction from text window
• Learn OOP and GUI framework -> “Ordinary programs”– Programs with interaction from windows
• Network and Servlet framework -> dynamic webpages (i.e. e-shops)
Copyright 2000 Kasper B. Graversen 16
StreamsStreams
• A stream is the idea of information floating without having a beginning or an end.
• Such flows could be the input from the keyboard.
• To read the keyboard we use a “straw” and “suck up” information
Copyright 2000 Kasper B. Graversen 17
The System ClassThe System Class
• The System is a special class as it is always available.
• System has three streams – in - reading the keyboard, – out,err - outputting on the screen.
• System also has the functionality to tell the time on the computer
• Javadoc on System
Copyright 2000 Kasper B. Graversen 18
Java’s I/O modelJava’s I/O model
• Very complex and confusing - even for more experienced programmers.
• Basic concept is combination of specialization
resource
resource
reader
compression reader
resourcebookkeeping reader
encryptionreader
reader
Copyright 2000 Kasper B. Graversen 19
Buffered I/OBuffered I/O
• A lot of speed is gained by reading larger chunks of information rather than a single information at a time
• The BufferedReader()enables reading lines rather than reader characters
Copyright 2000 Kasper B. Graversen 20
Reading from the keyboardReading from the keyboard• Difficult compared to other languages - can
be tough on the beginner.
• Many authors create their own I/O classes - so did miss Bishop.
BufferedReader in = new BufferedReader( new InputStreamReader(System.in));System.out.print(“Seconds since 1.1.1970?”);String s = in.readLine();Integer integer = new Integer(s);long seconds = integer.longValue();if(seconds > (System.currentTimeMillis()/1000)) System.out.print(seconds +“ too high an estimate”);else System.out.print(seconds + “ too low an estimate”);
Copyright 2000 Kasper B. Graversen 21
Reading from the keyboardReading from the keyboard• Continued…
import java.io.*;
class …{ void …() { try { … code from previous slide } catch(IOException e) { System.out.print(“oops something went wrong”); e.printStackTrace(); }
use java’s I/O
Copyright 2000 Kasper B. Graversen 22
ExceptionsExceptions
• Usage– Either catch the exceptions in the method– declare the method to possibly throwing an exception
– If we denote throwing we must have code which may throw the exception
– Handling must take place (elsewhere)
public int readNo () throws IOException{ …}
Copyright 2000 Kasper B. Graversen 23
How do we know what How do we know what exceptions are thrown?exceptions are thrown?
• Let the compiler tell us
• Use the javadoc
Copyright 2000 Kasper B. Graversen 24
Why now all these Why now all these try..catch?
• We separate error handling from logic
• Much more expressive than a return value false or -1 which before the invention of exceptions were the “de-facto standard”
• More on exceptions next time…
Copyright 2000 Kasper B. Graversen 25
Access modifiersAccess modifiers
• Four different types– public– package– protected– private
• Applied to– attributes,
constructors, methods
These we will use in the course
You will use when you get more advanced
May seem the same to you
Copyright 2000 Kasper B. Graversen 26
HorseRace cheater HorseRace cheater (Access modifiers)(Access modifiers)
Oops!Oops!
Horse h = new Horse(“Strong anton”, 99);
Horse“strong anton”2
h.energy = 99;
99
Copyright 2000 Kasper B. Graversen 27
The problemThe problem
• We have built a class with a constructor ensuring “correct” initialization.
• However, there is no assurance that the objects are later invalidated.
Copyright 2000 Kasper B. Graversen 28
SolutionSolution• Protect attributes and create indirect access.
• Explanation– public = “available outside the object”– private = “not available outside the object”
• Why is the setEnergy() construction better?
class Horse{ private int energy; public void setEnergy(int energy){…}}
In setEnergy() we can control the values
Copyright 2000 Kasper B. Graversen 29
Using Access modifiersUsing Access modifiers• To the programmer of the object there is no
difference, whether a modifier is specified or notpublic boolean setEnergy(int energy){ if(energy > 0 && energy < 3) { this.energy = energy; return true; } return false;}
Why did introduce a return value?
It’s always nice to know if things are well, to be able to notify the user, maybe even letting him choose another value.
I.e. a printer set to print -10 pages.
Copyright 2000 Kasper B. Graversen 30
Using access modifiersUsing access modifiers• How do we make field foo
– R/W– R
– W
– No access
– Controlled R/W
public int foo;
private int foo;public int getFoo()
private int foo;public boolean setFoo()
private int foo;
private int foo;public boolean setFoo()public int getFoo()
Copyright 2000 Kasper B. Graversen 31
Using access modifiersUsing access modifiers
• What other and equally profound consequence exist when using public/private for all methods, constructors and attributes?
• Reduction of number of accessible fields and methods when looking at the object “from the outside”
• Reusing code is much simpler due to a simple interface
Copyright 2000 Kasper B. Graversen 32
Using access modifiersUsing access modifiers• An object without access modifiers
Objectmethods
Attributes
Copyright 2000 Kasper B. Graversen 33
Using access modifiersUsing access modifiers
An object using access modifiers
Copyright 2000 Kasper B. Graversen 34
Using access modifiersUsing access modifiers• An example
class BankAccount{
public void list(); public void deposit(); public void withdraw(); public int getBalance();
}
private int balance;private Date created;private Date closed;
private void interest(double rate);private void logging(Date now);private void taxInformation();
Copyright 2000 Kasper B. Graversen 35
What is What is protected/package
• Protected– Used in conjunction with inheritance
• Package– We can assemble several classes in a package. The
modifier denotes everyone in the package can access.
– If no package is specified for a class, the class is put in the “unnamed package”
Packages shipped from Java
Copyright 2000 Kasper B. Graversen 36
Specifying access modifiersSpecifying access modifiers• public public• protected protected• private private• package nothing!
• So till now we’ve been using package as access modifier (of course with me not telling you that :-)
• As we do not use packages all classes resides in the same package and hence public/package seems to have the same effect
Copyright 2000 Kasper B. Graversen 37
Java Gently packagesJava Gently packages
• Display - easy creation of GUI’s• Stream - easy I/O + nice printing
• Learn how to reuse others work
• Gives you easy access to difficult areas
• The packages may show very limiting
• When being shielded too much from reality understanding may lack behind, and weird errors and limitations may occur
Copyright 2000 Kasper B. Graversen 38
Reuse of JavaReuse of Java• Either have the class files residing in your
directory– makes a big mess
• Compress all files into one file and name it xxx.jar
• This jar file can either reside with your source files or at a completely different place
Copyright 2000 Kasper B. Graversen 39
Reuse of JavaReuse of Java• Like Windows, the virtual machine looks for
files only at certain places on your hard drive. Precisely the places defined in the variable classpath
• Install procedures– Download the jg.jar from the course home page
• Copy it to c:\oop
• Add set classpath=%classpath%;c:\oop\jg.jarto c:\autoexec.bat
Copyright 2000 Kasper B. Graversen 40
Reuse of softwareReuse of software
• How do I estimate whether package X is worth re-using?
• Experience will help– Understand the underlying technology used and
its pros and cons– Is it easy to use? Does it feel natural?– Small but “deep” examples.
Copyright 2000 Kasper B. Graversen 41
Reuse of softwareReuse of software• “software” must be understood in a broader
sense.
• Using software (editors, compilers, debuggers, project management, various tools) can be a “big” part of being a software developer.
• Always weight the advantages compared to the time spent having the advantages
Copyright 2000 Kasper B. Graversen 42
The The DisplayDisplay package interface package interfacevoid println(String)
Write in right window
void prompt(String,[String|int|double])
Make textbox on left window with a name
void ready(String)
Let program wait for button press
int getInt(String)
double getDouble(String)
String getString(String)
Read value from a named textbox
where [, |, ] are meta-symbols
(see page 119).
Copyright 2000 Kasper B. Graversen 43
The The DisplayDisplay package packageimport javagently.*;
class DisplayTest{ public static void main(String[] args) { Display d = new Display("Test"); d.prompt(“hour”, 11); d.prompt(“min”, 30); d.prompt(“add minutes”, 15); d.ready(“Press ready when hours…”); }}(result is found on page 118)
Copyright 2000 Kasper B. Graversen 44
The The StreamStream package package
• Properties of files– Read– Write– No update! re-write the whole file
• States involved when using files– opening– R/W– closing
Copyright 2000 Kasper B. Graversen 45
The The StreamStream package interface package interfacein
int readInt()
double readDouble();
String readString();
char readChar();
out
void println([String|int|double|char])
void print([String|int|double|char])void close() (see page 123)
Copyright 2000 Kasper B. Graversen 46
The The StreamStream package package
Reading from the keyboardimport java.io.*;
import javagently.*;
class StreamTest
{public static void main(String[] args) throws IOException
{
Stream in = new Stream(System.in); System.out.println("name: ”+in.readString());
}
}
know IOExceptionUse JG’s code
Copyright 2000 Kasper B. Graversen 47
More on I/OMore on I/O
• Fundamentally I/O ensures reuse of data
• It enables processing of data, storing the result for use by other programs
• Maybe even more important it enables persistence - which is an academic word for:
When the computer is turned off and then on again, the program can continue from where it was last stopped.
Copyright 2000 Kasper B. Graversen 48
More on I/OMore on I/O• Java has several aspects of supporting
persistence.
• Persistence in java is semi-automatic– You have to invoke the read/write calls– It will read/write data or even objects
• We will dig into the most simple form - and we will build it ourselves.
• Why? Our webshop project at the end of the course must stand that the computer might be turned off.
Copyright 2000 Kasper B. Graversen 49
More on I/OMore on I/O• At first this problem seems easily solved.
• Programming it the right way can be difficult if
• We require NO data at all may be lost – even if the program is not shut down properly, – even if the power is turned of in the middle of
writing data
• We require easy usage so the programmer do not forget to read/write
Copyright 2000 Kasper B. Graversen 50
The endThe end