imperative programming nvon neumann’s computer model: computer = + memoryprocessor to store values...
Post on 20-Dec-2015
225 views
TRANSCRIPT
Imperative programming
Von Neumann’s computer model:
computer=+
memory processor
to store values
to execute instructions
Instructions
Instruction:direction to modify memory
Program:long sequence of instructions,which are executed one by oneby the processor
instructions are stored in memory, too, but don’t modify themselves
Programming languages
Programminglanguage:notation for programs
since 1945:3000 different languages published
History of programming languages
1945
1950
1955
1960
1965
1970
1975
1980
1985
1990
1995
2000
Assembler
Mach.lang.
Fortran
Algol
Basic
Pascal
Simula
C
C++
Java
Cobol
SQL
Lisp
Prolog
Haskell
FunctionalProgramming
ImperativeProgramming
Databases(SCI251)
Memory capacity
1965s: 8 kB RAM punched cards 1970s: 16 kB RAM tape 1980s: 64 kB RAM floppy 1985s: 640 kB RAM 1990s: 4 MB RAM harddisk 1995s: 16 MB RAM CD 2000s: 128 MB RAM DVD
Problems associated with programming
in olden times:how can memory be utilized efficiently?
now:how can memory be understood in full?
Order out of chaos
person
club
league
federation
county
province
state
country
unionunion
employee
department
division
company
holding
lecturer
chair
department
faculty
university
Memory structure
named memory location
group of variablesbelonging together
variable
object
object group of objects
belonging together
Program structure
direction to change memory
group of instructions belonging together
statement
method
class group of methods
belonging together
Programming paradigms
Imperative
Procedural
Object- oriented
Fortran Basic
Pascal C
C++ Java
Declarative
Functional
Logic
Lisp
Haskell
Prolog
Assembler
Algol
Simula
Excel
Java why?
Imperative and procedural and object oriented
Fun to learn Extensive libraries
also for window programs Cool : programming for the Internet
Machine language
Instructions are specificfor a target processor
Translating 1/4: Assembler
An assembler translates machine-specific source code to object code,which is executed subsequently
assembler
assembler
Higher programming language
Single program can be translated for many different processors
Source code also intelligible for human writer/reader
Translating 2/4: Compiler
A compiler translates source code to machine specific object code,which is executed subsequently
compiler
compiler
Translating 3/4: Interpreter
A processor sepcific interpreterreads source code and executes it
interpreter
interpreter
Translating 4/4: Compiler+Interpreter
A universal compiler translates source code to byte code, which can easily be interpreted
compiler
interpreter
interpreter
Implement
Programming cycle
Edit
Compile
Run
Specify
Model
Java program types
Java Appletprogram “lives” on a WWW-page
Java Applicationprogram has window of its own
Javascriptprogram assists in web page construction
JavaScript is not Java!
Java versus JavaScript
Imperative Can be Internet based Object oriented Compiled byte code In fixed rectangle Extensive method
libraries For programmers
Imperative Internet based “Only” procedural Interpreted directly Influences browser Fixed number built-
in methods For web designers
Source code structure
Statements to modify memory
Statements are grouped in methods
Methods are grouped in classes
which might be calls to yet other methodsso “where am I” tracking might grow complicated!
Statement forms
Assignment -statement:modify memory
Call of another method:first execute statements of that method, then continue were you were
Object orientation
Object:part of memory that belongs together
Object oriented programming:methods involves (mostly) an objectmentioned at the call
Example Java program
one class
...with onemethod
...with onestatement
braces delimitclass and method
import java.awt.Graphics;import java.applet.Applet;
public class Hello extends Applet{ public void paint (Graphics g) { g.drawString(“Hello!”, 20, 20); }}
Class and method header
public:may be used from outside
name:determined byprogrammer
import java.awt.Graphics;import java.applet.Applet;
public class Hello extends Applet{ public void paint (Graphics g) { g.drawString(“Hello!”, 20, 20); }}
Statement: method call
statement:method call
method namealwaysa dot
otherdetails
import java.awt.Graphics;import java.applet.Applet;
public class Hello extends Applet{ public void paint (Graphics g) { g.drawString(“Hello!”, 20, 20); }}
object involved
Communication with browserclass is
extension oflibrary class
Applet
... which comesin useful!
browser callspaint method,
providing aGraphics object ...
import java.awt.Graphics;import java.applet.Applet;
public class Hello extends Applet{ public void paint (Graphics g) { g.drawString(“Hello!”, 20, 20); }}
Class libraries
library classesmay be used...
if they areimported,
mentioning theirpackage
import java.awt . Graphics;import java.applet . Applet;
public class Hello extends Applet{ public void paint (Graphics g) { g.drawString(“Hello!”, 20, 20); }}
we get a parameter
Method header and call
we providethree parameters
methodheadermethod
call
import java.awt.Graphics;import java.applet.Applet;
public class Hello extends Applet{ public void paint (Graphics g) { g.drawString(“Hello!”, 20, 20); }}
WWW-page with Applet
special HTML-tag
<APPLET>
byte code which resultsfrom compiling Hello.java
<HTML>Here is a <B>simple</B>applet: <BR>
<APPLET code = Hello.class width = 100 height= 50 ></APPLET></HTML>
Embedding an Appletimport java.awt.Graphics;import java.applet.Applet;
public class Hello extends Applet{ public void paint (Graphics g) { g.drawString(“Hello!”, 20, 20); }}
Hello.java
<HTML>Here is a <B>simple</B>applet: <BR>
<APPLET code = Hello.class width = 100 height= 50 ></APPLET></HTML>
Hello.html
compiler
Hello.class
SDK: Software Development Kit
Sun’s Java SDK
compiler:javac
bytecode-interpreter:
appletviewer
Integrated Development Environment: JCreator
JCreator: New File
JCreator: syntax highlighting editor
JCreator: Error messages
JCreator: Run applet
JCreator: set options
Run applet in Explorer
JCreator: JDK help
Summary
Imperative programming:program consists of statements,modifying memory
Object oriented programming:variables belonging togetherare grouped in objects
Summary
Statement :direction to modify memory
Method :named group of statements
Class :named group of methods
Summary
Translating higher language (source code)
to machine language (object code)
Assembler Interpreter Compiler Compiler - bytecode - interpreter
Summaryimport java.awt.Graphics;import java.applet.Applet;
public class Hallo extends Applet{ public void paint (Graphics g) { g.drawString(“Hallo!”, 20, 20); }}
Hello.java
<HTML>Hier is een <B>simpel</B>applet: <BR>
<APPLET code = Hallo.class width = 100 height= 50 ></APPLET></HTML>
Hello.html
compiler
Hello.class
we get a parameter
Summary
we providethree parameters
method-headermethod-
call
import java.awt.Graphics;import java.applet.Applet;
public class Hallo extends Applet{ public void paint (Graphics g) { g.drawString(“Hallo!”, 20, 20); }}
Class and method header
method fromclass Graphics
other methodsfrom Graphics
import java.awt.Graphics;import java.applet.Applet;
public class Hello extends Applet{ public void paint (Graphics g) { g.drawString(“Hello!”, 20, 20); }}
g.drawLine(10,20,50,60);g.fillRect (70,30,20,20);
Methods from Graphics
drawString drawLine drawRect drawOval fillRect fillOval setColor
hello
x
y
determines color of subsequent drawing
Classes and objects
Class describesobject capability
Object can do andremember things
Class also provides constants
... (Graphics g)
{ g.drawLine(10,20,50,60); g.fillRect (70,30,20,20); g.setColor( Color.blue ); g.fillRect (30,50,20,20);
g.setColor( Color.blue );}
method fromclass of object g
Colors
redgreenyellow
blue
cyan magenta
white
black
Color .
Drawing
g.setColor( Color.white );g.fillRect(0,0,200,100);g.setColor( Color.black );g.fillRect(10,0,10,100);g.fillRect(50,0,10,100);g.fillRect(90,0,10,100);g.fillRect(0,40,200,10);g.fillRect(0,70,200,10);g.setColor( Color.blue );g.fillRect(0,50,10,20);g.setColor( Color.red );g.fillRect(100,0,100,40);
Composition with blue and red (freely after Piet Mondrian)
Modifying the drawing
Correction of bar width
Correction of picture height
Correction of picture width
g.setColor( Color.white );g.fillRect(0,0,200,100);g.setColor( Color.black );g.fillRect(10,0,10,100);g.fillRect(50,0,10,100);g.fillRect(90,0,10,100);g.fillRect(0,40,200,10);g.fillRect(0,70,200,10);g.setColor( Color.blue );g.fillRect(0,50,10,20);g.setColor( Color.red );g.fillRect(100,0,100,40);
lots of work ...
Variables
g.fillRect(10, 0, 10, 100);g.fillRect(50, 0, 10, 100);g.fillRect(90, 0, 10, 100);g.fillRect(0, 40, 200, 10);g.fillRect(0, 70, 200, 10);
g.fillRect(10, 0 ,bar, height);g.fillRect(50, 0, bar, height);g.fillRect(90, 0, bar, height);g.fillRect(0, 40, width, bar);g.fillRect(0, 70, width, bar);
bar = 10;width = 200;height = 100;
int bar, width, height;
use of variables
assignmentstatements:variables get
a value
declaration:announcement
of variablesand their type
Method call
Assignment statement
Statement forms
object . method ( parameters ) ;
variable = value ;
becomes
Declarations
Declaration structure
zero or more
int: whole numbers double: floating point numbers class name : object variables
type variabele , variabele ;
Variables
g.fillRect(x1, 0 ,bar, height);g.fillRect(x2, 0, bar, height);g.fillRect(x3, 0, bar, height);g.fillRect(0, y1, width, bar);g.fillRect(0, y2, width, bar);
x1=10; x2=50; x3=90;y1=40; y2=70;
int x1, x2, x3, y1, y2;
g.setColor( Color.blue);g.fillRect(0, y1+bar, x1, y2-y1-bar );
x1 x2 x3
y1
y2
Expression:program phrase having a value
Use of expressions: Right hand side of assignment
statement
Method parameter
Expressions
x3 = x2+40 ;
g.fillRect(0, y1+bar, x1, y2-(y1+bar) ) ;
expressie
Expression structure
constant
variable
... operator ...
( ... )
5
hoogte
x + y
(y + 1)
+ 1
x -
expressionexpression
Operators
+ addition - subtraction * multiplication / division % remainder after division
division of int values:result is truncated!
14 / 3 == 4 14 == 4*3 + 214 % 3 == 2
Operator precedence
Multiplicationprecedes addition
Equal precedence:left to right
Want it otherwise?place parentheses!
1 + 2 * 3 == 7
and divisionand subtraction
10 - 5 - 2 == 3
(1+2) * 3 == 9
Program
asdimport java.awt.Graphics;import java.awt.Color;import java.applet.Applet;
public class Mondri extends Applet{ public void paint(Graphics g) { int breedte, hoogte, balk, x1, x2, x3, y1, y2; breedte = 200; x1 = 10; x2 = 50; x3 = 90; hoogte = 100; y1 = 40; y2 = 70; balk = 10; g.setColor(Color.white); g.fillRect(0, 0, breedte, hoogte);
g.setColor(Color.black); g.fillRect(x1, 0, balk, hoogte); g.fillRect(x2, 0, balk, hoogte); g.fillRect(x3, 0, balk, hoogte); g.fillRect(0, y1, breedte, balk); g.fillRect(0, y2, breedte, balk);
g.setColor(Color.blue); g.fillRect(0, y1+balk, x1, y2-(y1+balk) );
g.setColor(Color.red); g.fillRect(x3+balk, 0, breedte-(x3+balk), y1); }}
/* This applet displays a Mondrian like "composition with red and blue”*/
// position of lines
// background
// black bars
// colored fields
with comments
Comments
Intended for human readerignored by compiler
Two notations: from /* to */ from // to line end
Drawing
g.drawRect(20,60,40,40);g.drawLine(20,60,40,40);g.drawLine(40,40,60,60);
g.drawRect(70,60,40,40);g.drawLine(70,60,90,40);g.drawLine(90,40,110,60);g.drawRect(120,40,60,60);g.drawLine(120,40,150,10);g.drawLine(150,10,180,40);
public void paint(Graphics g){
}
big mess ofcoordinates!
New methods
Method:named group of statements
method call executesits body
private void drawHouse(…){ … . drawRect (…); … . drawLine (…); … . drawLine (…);}
public void paint(Graphics g){ … . drawHouse (…); … . drawHouse (…); … . drawhouse (…);}
private void drawHouse(…){ … . drawRect (…); … . drawLine (…); … . drawLine (…);}
public void paint(Graphics g){ … . drawHouse (…); … . drawHouse (…); … . drawHouse (…);}
Parameters
which Graphics objectis involved?
declaration of extra
parameter
private void drawHouse (Graphics gr, …){ gr . drawRect (…); gr . drawLine (…); gr . drawLine (…);}
pass extraparameter
public void paint(Graphics g){ … . drawHouse (g, …); … . drawHouse (g, …); … . drawHouse (g, …);}
public class Houses extends Applet{
}
public void paint(Graphics g){ … . drawHouse (g, …); … . drawHouse (g, …); … . drawHouse (g, …);}
public void paint(Graphics g){ … . drawHouse (g, …); … . drawHouse (g, …); … . drawHouse (g, …);}
The object this
which ??? objectis involved?
private void drawHouse (Graphics gr, …){ gr . drawRect (…); gr . drawLine (…); gr . drawLine (…);}public void paint(Graphics g){ this . drawHouse (g, …); this . drawHouse (g, …); this . drawHouse (g, …);}
which Houses objectis involved?
this: the objectalready involved
with paint
public void paint(Graphics g){ this . drawHouse (g, …); this . drawHouse (g, …); this . drawHouse (g, …);}
More parameters
draw threeslightly different
houses
even moreparameters!
public void paint(Graphics g){ this . drawHouse (g, 20,100, 40); this . drawHouse (g, 70,100, 40); this . drawHouse (g, 120,100, 60);}
Parameters
(x, y-w) (x+w,y-w)
(tx,ty)
(x,y)w
private void drawHouse (Graphics gr, … ){
gr . drawRect (…); gr . drawLine (…); gr . drawLine (…);}
private void drawHouse (Graphics gr, int x, int y, int w){ int tx, ty; tx = x + w/2; ty = y - w - w/2; gr . drawRect (x, y-w, w, w); gr . drawLine (x, y-w, tx, ty); gr . drawLine (tx, ty, x+w, y-w);}
private void drawHouse (Graphics gr, int x, int y, int w){ int tx, ty; tx = x + w; ty = y - w – w/2; gr . drawRect (x, y-w, w, w); gr . drawLine (x, y-w, tx, ty); gr . drawLine (…);}
private void drawHouse (Graphics gr, int x, int y, int w){
gr . drawRect (x, y-w, w, w); gr . drawLine (…); gr . drawLine (…);}
private void drawHouse (Graphics gr, int x, int y, int w){
gr . drawRect (…); gr . drawLine (…); gr . drawLine (…);}
Flexibility
The more parameters, the more flexible the method
(x,y)w
h
roofh
private void drawHouse(Graphics gr, int x, int y, int w, int h, int roofh, Color c, Color roofc, … ) {
and the morecumbersome to call...
Flexibility
Many parameters: hard to program
now easy to extend later
Few parameters: easy to prgram
now might be hard to
extend later
Communication among methods
Parameters :caller passes value to method
Method result :methods returnsvalue to caller
like amathematical
function
Methods with result
private int square (int x){ return x*x ;}
result type
value of resultin special return statement
Methods with result
first, somestatements
private int succesorsThirdPower (int x){ int s; s = x+1; return s*s*s ;}
Call of a void-methodis a statement
Method calling
g.drawString(“hello”, 10, 10) ;
x = this.square (5) ; … this.square (5) + 1 …
withoutresult
Call of a method with a resultis an expression
Expressions Constant Variable Operator expr. Expr. in parentheses
Call of methodwith a result
Statements Assignment
Call of void method
Return statement
Summary of constructs
x=5;
this.drawHouse (…);
return x*x;
5
xx+1
(x+1)
this.square(5)
Summary chapter 2
Statement :directions to change memory
Method :named group of statements
Class :named group of methods
Summary chapter 3+4
Calling methods in Graphics: drawLine, fillRect, setColor
Defining new methods e.g: drawHouse
Passing parameters to methods to make methods more flexible
Summary chapter 3+4
Variables to temporarily store values declaration states type, e.g. int, double
Expression calculation resulting in a value uses constants, variables, operators
Expression Constant Variable Operator expr. Expression in parenth.
Calling a method with a result
Statements Assignment
Calling a void method
Return statement
Summary chapter 3+4
x=5;
this.drawHouse (…);
return x*x;
5
xx+1
(x+1)
this.square(5)
Methods and objects
gr . drawString (“Hi”, 50, 50) ;
x = Math . sqrt(2.0) ;
method fromclass Graphics
Graphics objectinvolved
method fromclass Math
no object involved
static method
Parameters
not the parameter of paint !should always be a Graphics-object
Parameters make a method more flexible:it can be used in various situations
Parameters make an applet more flexible: it can be used in various situations
then what?
allowed: method of Greeting and Applet
Class extensions inherit methods
yielding a text String
public class Greeting extends Applet{ public void paint(Graphics g) { String person, greeting;
person = this . getParameter(“name”); greeting = “Hello ” + person + “!”; g.drawString(greeting, 50, 20 ); }}
public class Greeting extends Applet{ public void paint(Graphics g) {
this . getParameter(“name”);
}}
public class Greeting extends Applet{ public void paint(Graphics g) { String person;
person = this . getParameter(“name”);
}}
public class Greeting extends Applet{ public void paint(Graphics g) {
}}
public class Greeting extends Applet{ public void paint(Graphics g) {
this . ???
}}
like this one:
Passing parameters to Applets
<APPLET code=Greeting.class width=100 height=100>
</APPLET>
<PARAM name=name value=Jeroen>
as specifiedwhen calling
getParameter
will be the resultof the call to
getParameter
String
String object contains text Ways to obtain a String object:
constant calling a method yielding a String
calling an operatoryielding a String
this.getParameter (“name”)
“Hello” + person
“Hello”
not addition,but concatenation
Numbers versus texts
int x; x = 37;
String s; s = “37”;
x = 12 + 5; s = “12” + “5”;
17 “125”
x = Integer.parseInt(s); s = “” + x ;
conversion methodconcatenation operator
converts second operand to a String
whenever the first is
Applet with int parameters
public void paint (Graphics gr){
}
String text1, text2;
text1 = this.getParameter(“length”);text2 = this.getParameter(“width”);
length = Integer.parseInt(text1);width = Integer.parseInt(text2);gr.drawString(“perimeter: ” + 2*(length+width), 0, 0 );
int length, width;
Passing parameters toan Applet
<APPLET code=Rectang.class width=100 height=100>
</APPLET>
<PARAM name=length value=12><PARAM name=width value=8>
<APPLET code=Rectang.class width=100 height=100>
</APPLET>
<PARAM name=length value=7><PARAM name=width value=3>
Primitive versus Objecttypes types
int i; double d;
String s; Color c;
i
d
s
c
i = 5; d = 3.1415926;
s = “hello”; c = Color.blue;
3.1415926
5
object variablescontain references
How to obtain objects
String constants Constants in a class Result of a method Result of an operator Home made
“hello”
Color.blue
this.getParameter(“a”);
“total: ” + sum
new Color(0,0,0)
constructor method
Constructor method
Call of a constructor-methode: makes new object in memory treats it immediately returns the newly created object
new Color(0,0,0)
calling a constructoris an expression
Color c;c = gr.setColor( );
Colors
(255,0,0)(0,255,0)(255,255,0)
(0,0,255)
(0,255,255) (255,0,255)
(255,255,255)
(0,0,0)
Color(...)
Mixing colors
new Color(255, 0, 0)
new Color(255, 255, 0)
new Color(255, 64, 0) new Color(255, 128, 0) new Color(255, 192, 0)
Creating new objects
Color c;c = new Color(255,128,0);
Button b;b = new Button(“press here”);
ScrollBar s;s = new ScrollBar(...);
objects for interactionwith the user
Methods of Applet
paint
getParameter
init
add repaint
are calledby the browser
may be called from within the program
redefine inyour program!
Applet’s init and paint
init:called by the browserwhen the applet starts first
paint:called by the browsereach time the applet needs painting
just after init , but alsowhen a window re-appears
Applet’s add and repaint
add:to add interaction objects
repaint:to force an extra paint
typically: from init
Example: color mixerScrollBar Button
Using add
public class Mixer extends Applet{
public void init( ) {
} public void paint(Graphics gr) {
}
s = new ScrollBar(...);this.add( s );
.... s . getValue() ....
ScrollBar s; object-variable:is part of
this object
and therefore may be used inevery method!
ScrollBar s ;
Reacting on user actions
Event: action of the user click button slide scrollbar enter text in textfield ...
Event listener: object that reacts upon that
adding an Event listener to an interaction object
public class Mixer extends Applet{ Scrollbar s;
public void init( ) { s = new Scrollbar(...); this.add( s );
}
s . addAdjustmentListener (...);
the object that will be notifiedwhen the user adjusts scrollbar s
public class ...{ public void adjustmentValueChanged ( AdjustmentEvent e ) { // statements which will be executed // in response to user actions }}
Notification mechanism
implements AdjustmentListener
promise that adjustmentValueChanged will indeed be defined
public class Mixer extends Applet
{ ScrollBar s;
public void init( ) { s = new ScrollBar(...); this.add( s ); s . addAdjustmentListener ( ); }
Which event listener to use?
public void adjustmentValueChanged (AdjustmentEvent e){
}
Mixer object isevent listener of
its own scrollbar!
implements AdjustmentListener
this
// here you may use s and this
ScrollBar
public void init ( ){ s = new ScrollBar(...); this . add( s );
}
public void adjustmentValueChanged (AdjustmentEvent e){ this . repaint( );} public void paint (Graphics gr){
gr . fillRect( 0, 0, 100, 100 );}
int x; x = s . getValue( );gr . setColor( new Color(x, ..., ...) );
s . addAdjustmentListener (this);
Reacting on events
Interaction objectswith event listeners
ScrollBar s;s.addAdjustmentListener(this);
implements AdjustmentListenerpublic void adjustmentValueChanged (AdjustmentEvent e){...}
Button b;b.addActionListener(this);
implements ActionListenerpublic void actionPerformed (ActionEvent e){...}
Complete Color mixer
public class Mixer extends Applet implements ActionListener, AdjustmentListener { Scrollbar red, green, blue; Button black;
public void init ( ) {...} public void paint (Graphics gr) {...}
public void adjustmentValueChanged (...) {...} public void actionPerformed (...) {...}}
class Mixer: outline
object variables
redefiningApplet-methods
fullfilling promisesmade by implements
public void init ( ){ red = new Scrollbar(0,0,1,0,255); green = new Scrollbar(0,0,1,0,255); blue = new Scrollbar(0,0,1,0,255); black = new Button(“Black”); this . add(red); this . add(green); this . add(blue); this . add(black); red . addAdjustmentListener (this); green . addAdjustmentListener (this); blue . addAdjustmentListener (this); black . addActionListener (this);}
Mixer’s method init
creation ofinteraction
objects
building theuser interface
addition ofevent listeners
Mixer’s method paint
local declarations
getscrollbarpositions
draw coloredrectangle
public void paint (Graphics gr){ int rv, gv, bv;
rv = red . getValue(); gv = green . getValue(); bv = blue . getValue();
gr . setColor ( new Color(rv,bv,gv) ); gr . drawRect ( 20,60,260,220 );}
gr . drawString( rw+“ ”+gw+“ ”+bw );
public void adjustmentValueChanged (AdjustmentEvent e){ this . repaint( );}
Mixer’s Event-listenters
reation toScrollBar
reaction toButton
public void actionPerformed (ActionEvent e){ red . setValue(0); green . setValue(0); blue . setValue(0); this . repaint( );}
Summary Declarationsobject variable
parameter
local variable
public class Mixer ...{ Scrollbar red;
public void paint ( Graphics gr ) { int rv; rv = red . getValue( ); }}
permanently,assigned to in init
for communication,assigned to at call
temporarilyassigned to with an
assignment
Applet init paint getParamet
er add repaint
Summary AWT-classes
Graphics drawString fillRect setColor
Color String
ScrollBar getValue setValue
Button
ActionListener actionPerformed
AdjustmentListener adjustmentValueChanged
Summary chapter 4
Objects existing: parameter or constant result of method or operator home-made using new
Methods “involve” an object except: static methods
Summary chapter 5
String constants: “hello” operator + concatenates string-objects conversion from and to int:
s = n + “”;n = Integer.parseInt(s);
Color constants: Color.blue home made: new Color(r,g,b)
Summary chapter 5
Parameters for the entire Applet:
class Greeting extends Applet{ void paint(Graphics gr) { person = this.getParameter(“name”); }}
<APPLET code=Greeting.class width=100 height=100> <PARAM name= name value=Jeroen></APPLET>
Summary chapter 6
Applet-methods are inherited byextension classes Intended to call
getParameterrepaint
Intended to re-defineinitpaint
for creation ofinteraction objects
Class challange
How to make interaction componentsand how to react on their use?
Write a program showing a Scrollbar,and beneath it a numerical representationof its value
now!approx 5 min.
peeking at ch. 6 is allowed,but try first without that!
public class Interact extends Applet
{
}
Interaction
public void init(){ s = new Scrollbar(0,0,1,0,100); this . add(s);}public void paint(Graphics gr){ gr.drawString( s.getValue()+””, 50,50);}public void adjustmentValueChanged(...){ this . repaint();}
Scrollbar s;
implements AdjustmenListener
s.addAdjustmentListener(this);
while ( x<1000 ) x = 2*x;
public void paint (Graphics gr){ int x; x = 1;
gr . drawString( “” + x, 10, 10);}
Repeating statements
the body isexecuted over
and over
while thecondition
holds...
X 12481632641282565121024
Repeating multiple statements
int x, t;x=1; t=0;while ( x<1000 ){ x = 2*x; t = t+1;}
return t;}
n
private static int twoLog (int n){
braces pack twostatements into
a compound one
counter countsthe numberof doublings
Repetition with a counter
public void paint (Graphics gr){ int t; t=0; while ( t<10 ) { gr.drawString( “:-)”, 0, 20*t ); t = t+1; }}
counter controlsnumber of iterations
and comes inuseful
Class challenge
Write a method power having two parameters base (real number) exponent (natural number)
calculating
baseexponent
while ( t<n ){ t = t+1 ;}
t = 0;
private static double power (double x, int n){
}
Power method
return result;
result = result * x ;
result = 1;int t; double result;
Comparison operators
< less than <= less than or equal > bigger than >= bigger than or equal == equal to != not equal to
x=5 x becomes 5 !x==5 is x equal to 5 ?
Expressions
Expression with numeric value
Expression with text value
Expression with truth value
2 * (length + width)
“Hello ” + person
counter < exponent
type int
type boolean
type String
primitive
object-
primitive
Boolean expressions
Comparing values
Combining other Boolean expressions using logic operators && and || or ! not
x <= y
x<0 && y>0
! (x==0 && y==0) x!=0 || y!=0
George Boole
(1815-1864)
Constants
Constants with numeric value
Constants with text value
Constants with truth value
2
“Hello”
true
-5 137
“@#$%” “123” “”
false
“true”
Using Boolean expressions
As condition of a while statement
As right hand side of an assignment
As method result
while (x<10) ...
boolean b; b = x<10 ;
return x<10 ;
Class challenge
Write a method divisible , which determines whether x is divisible by dprivate static boolean divisible (int x, int d){
}
x%d == 0return ; truth valueas a result
Class challenge
Write a method smallestDivisor , whichdetermines the smallest divisor of xprivate static int smallestDivisor (int x){
}
int d;d = 2;
while ( ! divisible(x,d) ) d = d+1;
return d ;
try them all,one at a time
Changing variables
Shorthand notations:
x = x * 2 ;
old valuebecomesnew value
x = x * 2 ; x *= 2 ;
x = x + 5 ; x += 5 ;
x = x + 1 ; x += 1 ; x ++ ;
is multiplied by
is incremented with
is incremented
Repetition with a counter
int t ;
t = 0;while ( t<x )
t ++ ;}
{ // do something // useful with t
for ( t=0 ; t<x ; t++ )for
for-statementinitialisation
int t ;for ( t=0 ; t<x ; t++ )
condition tocontinue
step to next
gr.drawString( “#”, 0, t*10 );
for ( t=1 ; t<=x ; t++ )
for ( t=x ; t>=0 ; t -- )
for ( t=2 ; !divisible(x,t) ; t++ )
Repeated repetition
Body of a for-statement is a statementwhich may be a for-statement itself!
int x, y;for (y=0; y<10; y++) for (x=0; x<10; x++) gr.drawString( “+”, 10*x, 10*y );
y
+ + + + + + + + + ++ + + + + + + + + ++ + + + + + + + + ++ + + + + + + + + ++ + + + + + + + + ++ + + + + + + + + ++ + + + + + + + + ++ + + + + + + + + ++ + + + + + + + + ++ + + + + + + + + +
++ ++ + ++ + + ++ + + + ++ + + + + ++ + + + + + ++ + + + + + + ++ + + + + + + + +
Extreme cases
Zero repetitions
for (y=0; y<0; y++) gr.drawString(“hi”, 10, 10);
Infinitely many repetitions
while (true) audio.play( );
gr.drawString(“hi”, 10, 10); this statmentwill never be
executed!
Unintensional infinity
x=1;counter = 0;while (counter<10) x = x*2; counter = counter+1;{
}
forgot thebraces...
Compiler messages
Error messages variabele not declared missing semicolon ...
Warnings unreachable code statement has no effect while-statement doesn’t terminate
this warning istheoreticallyimpossible!
The Halting-problem is unsolvable
boolean stops (String filename){ ....}
void clever (String filename){ while ( stops(filename) ) x++;}
Ha! What about this?
Not so!This method
solves it:
stops( “Clever.java” )
what is thevalue of:
?
The Halting-problem is unsolvable
void clever (String filename){ while ( stopt(filename) ) x++;}
stops( “Clever.java” )
Two possibilities: “Clever” does stop
“Clever” doesn’t stop
...so stops returns true
...so clever hangs!
...so stops returns false
...so clever stops immediately!
contradiction!
thus, stops is impossible to write
Other Halting -like problems
Will a statement be executed? Is a program a virus?
but what about existing virus scanners? either too strict: false alarms or too generous: some viruses passed
irritating
dangerous
Example: interst rates
TextField -objectenfor user interaction
TextField-objectspossess an
ActionListener
public class Interest extends Applet implements ActionListener{ TextField startT, renteT;
public void init ( ) {...} public void paint (Graphics gr) { ... }
public void actionPerformed (...) { this.repaint(); }}
Outline of class Interest
object-variabels
re-defining Applet-methods
fulfillingimplements promise
public void init ( ){ startT = new TextField(“100”, 8 ); rateT = new TextField(“5”, 4 );
this . add(startT); this . add(rateT);
startT . addActionListener (this); rateT . addActionListener (this);}
Interest ’s method init
creation ofinteraction
components
setup ofuser interface
addition ofevent listeners
public void paint (Graphics g){
}
Interest ’s method paint
startT.getText()rate.getText()
start = Integer.parseInt( );rate = Integer.parseInt( );
for (year=0; year<=10; year++){ gr.drawString( “year:”+year + “amount:”+captial, ... );
}
capital = start;
captial *= (1 + 0.01*rate) ;
int start, rate, year; double capital;
Class challenge
Write a method root , calculating the square root of a non-negative double
Without using Math.sqrt !
Use Newton approximation:when y approximates sqrt(x),then the average of y and x/yis a better approximation
private static double sqrt (double x){
}
Sqrt method
double y;y = 1;
return y;
y = (y + x/y) / 2 ;while ( y*y != x )
does it stop?
mathematician:no, equality hold only in limiting case
programmer:yes, precision islimited
computer scientist:no, roundof errorsprohibit reaching astable state
while ( Math.abs (y*y - x) <0.000001 )
safer:
Structure of repetition
Initialisation
Repeated improvement
Use of result
captial=start; y=1; total=0;
captial*=(1+0.01*rate); y=(y+x/y)/2; total+=x;
gr . drawString (“”+captial);
return y;
sb . setValue ( total );
DrawString or return?
gr.drawString (x, ...)result immediately visible
return x;result is returned to caller,who can decide what to do with it
more flexibleuseful for
for “simple” results
useful for “complicated” layout
Program constructions
Statements Assignment Call void-methode return-statement while- statement for- statement { ... } - grouping
Expressions Constant Variable Call methode Expression with
operators Expression with parenth. new-expression
to do to calculate
Program constructions
Declaration Local variable
for temporary use Object-variable
permanent part of object
Parameterfor passing values to methods
Type Primitive type
int double boolean
Object-type Color, String etc. TextField, Button etc. Applet, Hallo, etc.
states typeof variables
set of possible valuesof an expression
Summary ch.7
while-statement: repeating statements
while (x<1000) x = 2*x;
body is repeatedlyexecuted
while condition is valid
Summary ch.7
for-statement: repetition with a counter
int t ;
t = 0;while ( t<x )
t ++ ;}
{ // do something // useful with t
for ( t=0 ; t<x ; t++ )
Summary program constructions
Statements Assignment Call void-method return-statement while-statement for-statement { ... } - grouping
Expressies Constant Variable Call method Expression with
operators Expression with parenth. new-expression
can be done can be calculated
Summary program constructions
Declaration Local variable
for temporary use Object variable
permanently part ofthe object
Parameterto pass values to amethod
Type Primitive type
int double boolean
Object type Color, String etc. TextField, Button etc. Applet, Hello, etc.
indicates variable type
set of possible valuesof a variable
Executing statements conditionally
statement is only executedwhen condition holds
statement is executed over and overwhile condition holds
if (temperature<0) gr.drawString(“It’s freezing!”, 10, 10);
while (temperature<0) temperature += 5;
Two alternatives
statement is only excecutedwhen condition doesn’t hold
if (temperatuur<0) gr.drawString(“It’s freezing!”, 10, 10);else gr.drawString(“It’s thawing.”, 10, 10);
Choice is a statementas any other
if (n%3==0) gr.drawString(n + “divisible”, 10, 10 );else gr.drawString(n + “indivisible”, 10, 10 );
for (n=1; n<20; n++)
*n
*n
if-statements acts asbody of for-statement
one statementas a body,
so no bracesneeded
Multiple-statement body
braces group two statementsinto one
if (temperatuur<0) gr.drawString(“It’s freezing!”, 10, 10); gr.drawString(“Isnt’ that cold?”, 10, 20);
{
}
More than two alternatives
if (age<65) tf.setText(“Full fare”);else tf.setText(“Senior”);
if (age<12) tf.setText(“Railrunner”);
else
if (age<4) tf.setText(“Free”);
else
if-statement as a wholeis body of else-part
if-statement as a wholeis body of else-part
More than two alternatives
if (age<4) tf.setText(“Free”);else if (age<12)
tf.setText(“Railrunner”);else if (age<65)
tf.setText(“Full fare”);else tf.setText(“Senior”);
tf.setText(“Full fare”);else tf.setText(“Senior”);
tf.setText(“Railrunner”);else if (age<65)
exeption to ruleto indent the body
private String tariff(int age){
}
More than two alternatives
if (age<4) return “Free”;else if (age<12) return “Railrunner”;else if (age<65) return “Full fare”;else return “Senior”;
if (age<4) return “Free”;if (age<12) return “Railrunner”;if (age<65) return “Full fare”;return “Senior”;
return-statementends method body
Button b;public void init ( ){ radius = 100; b = new Button(“grow”); this.add(b); b.addActionListener(this);
Drawing circlesclass Cirkel extends Applet{
}
public void paint(Graphics gr){ gr.fillOval(150-radius,150-radius,2*radius,2*radius);}
int radius;public void init ( ){ radius = 100;
}public void actionPerformed(ActionEvent e){ radius += 10; this.repaint();}
implements ActionListener
Drawing circlesclass Cirkel extends Applet{
int radius;Button small, big;
public void init ( ){ radius = 10; small = new Button(“shrink”); this.add(b); big = new Button(“grow”); this.add(b); small.addActionListener(this); big.addActionListener(this);}
implements ActionListener
Drawing circles
public void actionPerformed(ActionEvent e){ if ( e.getSource() == small && radius>10 ) radius -= 10; if ( e.getSource() == big && radius<150 ) radius += 10;
this . repaint();}
equality ofButton-object-references)
public void actionPerformed(ActionEvent e){ if ( e.getSource() == small ) radius -= 10; if ( e.getSource() == big ) radius += 10;
this . repaint();}
Secret drawingclass Secret extends Applet{
public void paint (Graphics gr){ gr.setColor(Color.green); gr.fillOval(50,50,100,100); gr.setColor(Color.blue); gr.fillOval(81,85,8,8); gr.fillOval(111,85,8,8); gr.drawArc(75,75,50,50,225,90);
}
boolean open;public void init (){ open = false;
}
if (open){
}
TextField pass;
pass = new TextField(20); this.add(pass); pass.addActionListener(this);}
Secret drawingclass Secret extends Applet implements ActionListener{ boolean open; TextField pass;
public void actionPerformed (ActionEvent e){
open = true; this . repaint();
}
if ( pass.getText() . equals (“geheim”) ){
}
pass . setVisible(false);
operator == or method equals ?
== tests variable equality
equals tests String-contents equality
5
5
x
y
s
thoi
s
t
hoi
hoi
s
thoi
s
t
hoi
hoi
method for
String-objects
Min./max. thermometerclass Thermo extends Applet
{ ScrollBar meter; Button reset;
public void init (){ meter = new ScrollBar(ScrollBar.HORIZONTAL,0,1,-50,50); reset = new Button(“reset”);
}
this.add(meter); this.add(reset); meter.addAdjustmentListener(this); reset.addActionListener(this);
int minimum, maximum;
minimum = 0; maximum = 0;
impelements AdjustmentListener, ActionListener
Min./max. thermometerpublic void paint (Graphics gr){ gr.drawString( “hoogste ” + maximum, 50,50); gr.drawString( “laagste ” + minimum, 50,70);}public void adjustmentValueChanged(AdjustmentEvent e){
this.repaint();}
maximum =
minimum =
if (waarde>maximum) waarde;if (waarde<minimum) waarde;
int waarde;waarde = meter.getValue();
Interaction components
ScrollBar sb; sb = new ScrollBar(
hv, value, step, range); sb.addAdjustmentListener(
...);
n = sb.getValue(); sb.setValue(n);
TextField tf; tf = new TextField(
width); tf.addActionListener(...)
;
s = tf.getText(); tf.setText(s); n = Integer.parseInt(s);
Conversion
From String to int
String s; int n;n = Integer.parseInt (s);
From String to double
String s; double d; d = Double.valueOf (s); Double dob; obd = dob.doubleValue ();
Graph-drawing program
graph of theparabola
solutions according toabc-formula
entered values abc
Design of class Parabola
declaration Objectvariables method init method actionPerformed method paint method zeroes method axes method graph method parabola
makes interface
converts a,b,c
“manages” drawing
do the actual
drawing
calculates ax2+bx+c
Parabola: initclass Para extends Applet implements ActionListener{
TextField abox, bbox, cbox;double a, b, c;public void init (){ a = 0.5; b = 2.0; c = -4.0;
}
abox = new TextField( “”+a, 8 );bbox = new TextField( “”+b, 8 );cbox = new TextField( “”+c, 8 );this.add(abox); this.add(bbox); this.add(cbox);abox.addActionListener(this);bbox.addActionListener(this);cbox.addActionListener(this);
Parabola: actionPerformed
public void actionPerformed(ActionEvent e){
}
a =b =c =this.repaint ();
abox.getText()bbox.getText()cbox.getText()
Double.parseDouble( ); Double.parseDouble( );Double.parseDouble( );
Parabola: paintpublic void paint (Graphics gr){
}
zeroes
axes
graph
this .
this .
this .
(gr);
(gr);
(gr);
gr . setColor( Color.black );
gr . setColor( Color.red );
gr . setColor( Color.blue );
private void axes (Graphics gr){ gr.drawLine(0, 250, 500, 250); gr.drawLine(250, 0, 250, 500);}
Parabola: zeroespublic void zeroes (Graphics gr){
}
gr.drawString( (-b -root)/denomin + “ and ” +(-b+root)/denomin , 50, 50 );
root = Math.sqrt(discriminant);
discriminant = b*b - 4*a*c;denomin = 2*a;
if (discriminant<0) gr.drawString(“geen nulpunten”);else{
}
-b ± b2-4ac
2a
Parabola: graphpublic void graph (Graphics gr){
}
for ( x=0 ; x<500 ; x++ ){
}
y = this.parabool( x );
gr.drawLine( , , x, y );x-1 oldyoldy = y;
oldy = 0;
if (x>0)
scale = 0.03;
xw = scale * x ; w wy = yw / scale ;
( -250)
(int) (250-( ))
int x, y,oldy; double xw, yw, scale;
Summary lecture 5
if-statement if-else-statement
compare int with compare String with
x==y
s.equals(t)
Summary ch. 8
if-statement if-else-statement
compare integers with compare Strings with
x==y
s.equals(t)
Min./max. thermometerclass Thermo extends Applet
{ ScrollBar meter; Button reset;
public void init (){ meter = new Scrollbar(ScrollBar.HORIZONTAL,0,1,-50,50); reset = new Button(“reset”);
}
this.add(meter); this.add(reset); meter.addAdjustmentListener(this); reset.addActionListener(this);
int minimum, maximum;
minimum = 0; maximum = 0;
implements AdjustmentListener, ActionListener
Min./max. thermometerpublic void paint (Graphics gr){ gr.drawString( “hoogste ” + maximum, 50,50); gr.drawString( “laagste ” + minimum, 50,70);}public void adjustmentValueChanged(AdjustmentEvent e){
this.repaint();}
maximum =
minimum =
if (waarde>maximum) waarde;if (waarde<minimum) waarde;
int waarde;waarde = meter.getValue();
All aboutobjects and classes,
in one picture...
Program
statements
methods
class
variables
and Memory
objects
classclass
grouped in
grouped in
grouped in
have as type
change
treat
Class-definition
Description of methodseach consisting ofstatements
Description of objectsby declaration ofvariables
treat
class Counter ...{
... init(){
}
... actionPerformed(){
}
... paint(...){}
}
Button b;int t;
b = new Button();t = 0;
g.drawString(t...);
t = t+1;this.repaint();
x
Declaration
Declaration allocates space in memory For a primitive value
For an object reference
int x;
x = 5;
ScrollBar s;s = new ScrollBar(...);
5
s
as describedin class
Scrollbar
Creation of new objects
Objects having a library class as type
Scrollbar s;s = new Scrollbar(...);
type ofdesired object
Objects having ahome-made class as type
Thermo t; t = new Thermo( );
this is doneby the browser
t . init ( );t . paint (...);
Creation of objects
Structure of the objectis described in the class
meter
min max
Thermo
browser’scurrentapplet
inherited
declared in the class
class Thermo
{
}
Scrollbar meter;int min, max;
// methods...
extends Applet
meter
min max
Thermo
browser’scurrentapplet
Call of init
reset
this
Scrollbar
Button
00
public void init ( ){
}
Button reset;min = 0; max = 0;meter = new ScrollBar(...);reset = new Button(...);
Call of init
meter
min max
Thermo
browser’scurrentapplet
reset
this
Scrollbar
Button
00
}
this . add(meter);this . add(reset);reset . addActionListener(this);meter . addAdjListener(this);
added
adjListener
actListener
0 value
reset = new Button(...);
Situation aftercompletion of init
meter
min max
Thermo
browser’scurrentapplet
Scrollbar
Button
00
added
adjListener
actListener
0 value
Classes and objects
Class definition in libraryObject creation with new
Class definition in programObject creation by browser
Class definition in programObject creation with new
Thermo
Scrollbar
Space
Example: simulation of moving particles in a spaceSimulation -
object
Button -objects
Space -objects
Particle -objects
Class Simulationpublic class Simulation extends Applet{
Button step, auto;Space r1, r2, r3;
public void init ( ){ stap = new Button (“step”); auto = new Button (“start”); r1 = new Space(...); r2 = new Space(...); r3 = new Space(...); ...}
}
ClassSpace
yet to be defined!
Class Space
private class Space
{
}
Space is an extension of an
existinginteraction objectextends
Canvas
Particle d1, d2, d3;
// methods to be defined
every Space objecthas three Particleobjects of its own
Class Particle
private class Particle
{
}
Particle is not extending
anything
int x, y;
// method to be defined
position ofthe Particle
int dx, dy; Color col;
velocity of the Particle
browser’s currentapplet
Objects
Simulation
r1 r2 r3
stap
auto
d1 d2 d3
Space
d1 d2 d3
Space
x
y
dx
dy
col
Particle
x
y
dx
dy
col
Particle
x
y
dx
dy
col
Particle
x
y
dx
dy
col
Particle
x
y
dx
dy
col
Particle
x
y
dx
dy
col
Particle
d1 d2 d3
Space
Button
Button
x
y
dx
dy
col
Particle
x
y
dx
dy
col
Particle
x
y
dx
dy
col
Particle
inherited form Applet
declared in the class
inherited from Canvas
Construction of a new object
Allocate memory
Call constructor method
new expression does two things:
value is reference to the new object
r1
d1 d2 d3
Space
100 196
which can be stored
r1 = new Space ( ... ) ;
private Space ( ){
}
Constructor method
private class Space extends Canvas { Particle d1, d2, d3;
}
int width, int height
name is sameto that of the class
no resulttype!
inherited from
Canvas
this . setBackground (Color.gray);d1 = new Particle (...);d2 = new Particle (...);d3 = new Paticle (...);
this . setSize (width,height);
private class Particle {
}
Class Particle
int x, y, dx, dy; Color col;
public Particle (...) {...}public void setPos (...) {...}public void setVelo (...) {...}public void doStep ( ) {...}public void draw (Graphics g )
{...}
private class Particle {
}
Methods of class Particle
int x, y, dx, dy; Color col;
public void setPos (int x0, int y0){ x = x0; y = y0;}
public void draw ( Graphics gr){ gr . setcolor (col); gr . fillOval( x-3, y-3, 7, 7 );}
private class Particle {
}
Methods of class Particle
int x, y, dx, dy; Color col;public void doStep ( ){ x += dx; y += dy;
if (x<0){
}
x = -x;dx = -dx;
if (y<0) { ... }if (x>maxx) { ... }if (y>maxy) { ... }
private class Particle {
}
Methods of class Particle
int x, y, dx, dy; Color col;
public Particle (Color k, ){ col = k; maxx = maxy =}
Space r
r . getSize( ) . width;r . getSize( ) . height;
int maxx, maxy;
Summary of classes
class Simulation extends Applet impl ActList init actionPerformed
class Space extends Canvas Space paint
class Particle Particle setPos, setVelo, doStep, draw
public class Simulation extends Applet impl ActionListener {
}
Methods of class Simulation
Button step, auto; Space r1, r2, r3;
public void init ( ){ stap = new Button (“step”); auto = new Button (“start”); r1 = new Space (100, 196); r2 = new Space (196, 150); r3 = new Space ( 60, 75);
}
this.add(stap); this.add(auto);this.add(r1); this.add(r2); this.add(r3);step.addActionListener(this);auto.addActionListener(this);
public class Simulation extends Applet impl ActionListener {
}
Methods of class Simulation
Button step, auto; Space r1, r2, r3;
public void actionPerformed (ActionEvent e ){ if (e.getSource() == stap) this.doStep( ); else ...}
private void doStep ( ){
}
r1.doStep(); r2.doStep();r3.doStep();r1.repaint (); r2.repaint ();r3.repaint ();
private class Space extends Canvas {
}
Methods of class Space
Particle d1, d2, d3;public Space (int width, int height){ this.setSize (width, height); this.setColor (Color.gray); d1 = new Particle(Color.red, this); d2 = new Particle(Color.red, this); d3 = new Particle(Color.red, this); d1.setPos(30, 40); d1.setVelo(10,10); ...}
private class Space extends Canvas {
}
Method of class Space
Particle d1, d2, d3;
public void doStep ( ){ d1 . doStep (); d2 . doStep (); d3 . doStep ();}public void paint (Graphics gr){ d1 . draw (gr); d2 . draw (gr); d3 . draw (gr);}
Animation
Animationprogram shows changing picturesautomatically
Easily programmed using library class
Thread
“thread”of events
which occur,simultaneously
with other threads
Programming animations
animation . start ( ); this . run ( );
calls run of the object
that was passedto the constructor
Thread animation;animation = new Thread ( this );
and returnsimmediately
(even when run is still running)
Method run
class Simulation extends Applet{
}
implements Runnable
public void run ( ){
}
while (true)this . doStep ( );{
}
Thread . sleep (50);try{ Thread . sleep (50); }catch (Exception e){ }
infinite repetition!
millisecondsmilliseconds
if (moving){ auto . setLabel (“Start”); moving = false;}else{
}
Starting the animation
public void actionPerformed (ActionEvent e){
}
if (e.getSource ( )==auto){
}else this . doStep ( );
animation = new Thread(this);animation . start ( );auto . setLabel (“Stop”); moving = true;
Method run revisited
class Simulation extends Applet{
}
implements Runnable
public void run ( ){
}
while (true)this . doStep ( );{
}
try{ Thread . sleep (50); }catch (Exception e){ }
oneindige herhaling!
while (moving)
finite repetition.
if (beweging){ auto . setLabel (“Start”); beweging = false;}else{
}
Starting the animationrevisited
public void actionPerformed (ActionEvent e){
}
if (e.getSource ( )==auto){
}else this . doStep ( );
animatie = new Thread(this);animatie . start ( );auto . setLabel (“Stop”); moving = true;
(animation != null )animation = null;
The value null
null : reference to nothing
x = null;
x
null is a valid valuefor each object reference type
and use
What is object?declarations of object variables
Wat can you do with the object?method headers
How is it done?method bodies
Class design
Ways to design classes
Top-downstart with the most complicated classusing classes and methods which areyet to be written
Bottom-upstart with the simplest classcreating a library of methodswhich come in useful writingthe other classes
Summary ch. 9
Make objects of a home-made class variables: what is the object methods: what can the object do
Animation
Thread a;a = new Thread(this);a . start ( );
public void run ( ){ while (true) { this . doStep (); Thread . sleep(50); }}
Useful classes (1/4)
Things from reality String
length, equals, substring, concat Color
Color, red, green, blue, black, white Dimension
Dimension, getWidth, getHeight
Useful classes(2/4)
Computer related things BufferedImage
setRGB, getRGB, getGraphics AudioClip
play, stop, loop File
getName, getDirectory, exists, delete
Useful classes(3/4)
Objects that can do something for you Graphics
drawLine, fillRect, setColor StringTokenizer
nextToken, hasMoreTokens
Useful classes(4/4)
Interaction componentento use
ScrollBar Button TextField TextArea Label CheckBox
to extend Applet Canvas Frame
problems withversion management
Extending previous work
First try: “cut&paste”class Two{ int x, y;
int old ( ) { return x+y; }}
class Twee{ int x, y;
int old ( ) { return x+y; }
}
int z;
int extra ( ) { return x+y+z; }
Three
+1;
assymmetrical
clumsy
Extending previous work
Second try: “delegation”class Two{ int x, y;
int old ( ) { return x+y; }}
class Twee{ Twee t;
int old ( ) { return t.old(); }
}
int z;
int extra ( ) { return t.x+t.y+z; }
Three
Extending previous work
Third try: “subclasses”class Two{ int x, y;
int old ( ) { return x+y; }}
class Twee extends Two{
}
int z;
int extra ( ) { return x+y+z; }
Three
Subclasses
class Space extends Canvas
Space is a subclass of Canvas Canvas is the superclass of Space
Each Space-object is also a Canvas-object A Space-object is a special case of a
Canvas-object
Inheritance
Objects of a subclassinherit variables and methodsof the superclass
meter
min max
Thermo
inhertited
declaredby yourself
Superclasses in standard packages
Applet extends Panel Panel extends Container
superclass
super-superclass
Inherited methods
Applet inherits add from class Container
and manymany more...
Class hierarchies
Van
Car MotorBike
MotorVehicle Bicylce
Vehicle Plane
SteamBoat
MotorBoat SailBoat
Boat
Transporter
design:medium precedes
motorization
design:motorbike is moremotor than bike
Class hierarchies
Vehicle Boat
Transporter
class Vehicle extends Transporterclass Boat extends Transporter
“is a”
Class hierarchy in AWT
Applet
FileDialog
Frame Dialog
Panel Window TextArea TextField
Button Container Canvas Label TextComponent Scrollbar
Component
Button is a Component Applet is also a Component
(more precicely, a Container, and even a Panel)
Not every hierarchy isa class hierarchy
d1Particle
d2Particle
d3Particle
d1Particle
d2Particle
d3Particle
d1Particle
d2Particle
d3Particle
stepButton
autoButton
r1Space
r2Space
r3Space
browser's currentSimulatie
“has a”
Classes vs. Interfaces
Class:Group of methods and declarations
Interface:Group of method headers
“wish list”to be implemented
by another class
“Interface” in 3 readings
Hardware:connectors are the“face” of the computer
Software:buttons are the“face” of the software
Programming:methods are the“face” of the program
class Hallo implements ActionListener {
“GUI”
Interface hierarchy in AWT
Action-Listener
Adjustment-Listener
Component-Listener
Mouse-Listener
Event-Listener
Class hierarchy in AWT
ActionEvent AdjustmentEvent
KeyEvent MouseEvent
InputEvent FocusEvent
ComponentEvent
AWTEvent
EventObject
Everything in one hierarchy
String Component EventObject Image
Object
Methods in class Object : toString redefinable in a subclass clone makes exact copy
TextArea and String
class SymCount extends Applet
{
void init ( ){ input = new TextArea (5, 40); output = new TextField(40); count = new Button(“Count”); this.add(input); this.add(output); this.add(count); count.addActionListener(this);}
TextArea input; TextField output; Button count;
implements ActionListener
Useful classes (1/4)
Things from reality String
length, equals, substring, concat Color
Color, red, green, blue, black, white Dimension
Dimension, getWidth, getHeight
Useful classes(2/4)
Computer related things BufferedImage
setRGB, getRGB, getGraphics AudioClip
play, stop, loop File
getName, getDirectory, exists, delete
Useful classes(3/4)
Objects that can do something for you Graphics
drawLine, fillRect, setColor StringTokenizer
nextToken, hasMoreTokens
Useful classes(4/4)
Interaction componentento use
ScrollBar Button TextField TextArea Label CheckBox
to extend Applet Canvas Frame
problems withversion management
Extending previous work
First try: “cut&paste”class Two{ int x, y;
int old ( ) { return x+y; }}
class Twee{ int x, y;
int old ( ) { return x+y; }
}
int z;
int extra ( ) { return x+y+z; }
Three
+1;
assymmetrical
clumsy
Extending previous work
Second try: “delegation”class Two{ int x, y;
int old ( ) { return x+y; }}
class Twee{ Twee t;
int old ( ) { return t.old(); }
}
int z;
int extra ( ) { return t.x+t.y+z; }
Three
Extending previous work
Third try: “subclasses”class Two{ int x, y;
int old ( ) { return x+y; }}
class Twee extends Two{
}
int z;
int extra ( ) { return x+y+z; }
Three
Subclasses
class Space extends Canvas
Space is a subclass of Canvas Canvas is the superclass of Space
Each Space-object is also a Canvas-object A Space-object is a special case of a
Canvas-object
Inheritance
Objects of a subclassinherit variables and methodsof the superclass
meter
min max
Thermo
inhertited
declaredby yourself
Superclasses in standard packages
Applet extends Panel Panel extends Container
superclass
super-superclass
Inherited methods
Applet inherits add from class Container
and manymany more...
Class hierarchies
Van
Car MotorBike
MotorVehicle Bicylce
Vehicle Plane
SteamBoat
MotorBoat SailBoat
Boat
Transporter
design:medium precedes
motorization
design:motorbike is moremotor than bike
Class hierarchies
Vehicle Boat
Transporter
class Vehicle extends Transporterclass Boat extends Transporter
“is a”
Class hierarchy in AWT
Applet
FileDialog
Frame Dialog
Panel Window TextArea TextField
Button Container Canvas Label TextComponent Scrollbar
Component
Button is a Component Applet is also a Component
(more precicely, a Container, and even a Panel)
Not every hierarchy isa class hierarchy
d1Particle
d2Particle
d3Particle
d1Particle
d2Particle
d3Particle
d1Particle
d2Particle
d3Particle
stepButton
autoButton
r1Space
r2Space
r3Space
browser's currentSimulatie
“has a”
Classes vs. Interfaces
Class:Group of methods and declarations
Interface:Group of method headers
“wish list”to be implemented
by another class
“Interface” in 3 readings
Hardware:connectors are the“face” of the computer
Software:buttons are the“face” of the software
Programming:methods are the“face” of the program
class Hallo implements ActionListener {
“GUI”
Interface hierarchy in AWT
Action-Listener
Adjustment-Listener
Component-Listener
Mouse-Listener
Event-Listener
Class hierarchy in AWT
ActionEvent AdjustmentEvent
KeyEvent MouseEvent
InputEvent FocusEvent
ComponentEvent
AWTEvent
EventObject
Everything in one hierarchy
String Component EventObject Image
Object
Methods in class Object : toString redefinable in a subclass clone makes exact copy
TextArea and String
class SymCount extends Applet
{
void actionPerformed ( ActionEvent e ){ String s; int n; s = input.getText (); n = s.length (); output.setText ( “you typed ” + n + “ symbols” );}
TextArea input; TextField output; Button count;
implements ActionListener
String methods
int length ( ) boolean equals (String s) String concat (String s) String substring (int start) String substring (int start, int
end) String toUpperCase ( ) String toLowerCase ( )
concat and substring
String s, t, u, v, w;
s = “ham”; t = “burger”; u = s.concat(t); v = u.substring(3);
w = u.substring(3, 7);
s t u v w
ham burger
hamburger
burger
burg
hamburger012345678
s + t ;
“from andincluding”
“up to, butnot including”
Class challenge
Write a method startsWithhaving two String-parameters x and ythat determines whetherx is the initial part of y
Write a method containshaving two String-parameters x and ythat determines whetherx occurs anywhere inside y
Method startsWith
(String x, String y)
boolean
private static
part whole
{
}
y . substring
(0, x.length() ) x . equals (
)
return
;
startsWith
Methode contains
(String x, String y)
boolean
private static{
}
contains
y . substring(t)
startsWith(x, )if ( ) return true;
for (t=0; t<y.length(); t++)
return false;
int t;
More String-methods
boolean startsWith (String s) boolean endsWith (String s) int indexOf (String s)
private static boolean contains(String x, String y){ return y.indexOf(x)>=0 ;}
Stand-alone characters
String substring (int begin, int end)
String initial;initial = s . substring(0,1);
charcharAt (int position)
char first;first = s . charAt(0);
Primitive types
intwhole numbers -17, -5, 0, 3, 178
doublereal numbers 3.141, 2.0, -1.5E8
booleantruth values false, true
charsymbols ’A’, ’B’, ’Z’, ’a’, ’4’, ’#’, ‘:’
Class challenge
// write a static method that counts// how often a symbol occurs in a String
// example call:
int n;n = Demo . freq( “some text”, ’e’ );
// hint: use a for statement
Count symbol frequency
private static int freq(String s, char x){
s.charAt(t)==x
for (t=0; t<s.length(); t++)
if ( ) count++;
int count, t;count = 0;
return count;}
IBM/DOS
History of char
1970s: 6 bits = 64 symbols26 letters, 10 digits, 28 punctuation
1980s: 7 bits = 128 symbols+26 lowercase, +5 punct., 33 control
1990s: 8 bits = 256 symbols+letters with diacriticals
2000s: 16 bits = 65536 symbols+Greek, Cyrillic, Japanese,
Devangari, ...
ASCII
ANSI/ISO
Unicode
Character coding
bs tab lf cresc
sp ! " # $ % & ' ( ) * + , - . /0 1 2 3 4 5 6 7 8 9 : ; < = > ?@ A B C D E F G H I J K L M N OP Q R S T U V W X Y Z [ \ ] ^ _` a b c d e f g h i j k l m n op q r s t u v w x y z { | } ~ del
code 0
code 127
code 48
code 32
code 65
code 97
char specials
alfabetically orderedchar c;if ( ’A’<=c && c<=’Z’ ) …
convertable to intint n;n = c + 32;
and backc = (char) n;
Conversions Conversion to “larger” set
is always possible
double d; int n;d = n;
int n; char c;n = c;
Component x; Button b;x = b;
Conversion to “smaller” setis dangerous
n = (int) d;
c = (char) n;
b = (Button) x;
two symbols in the source,representing one character
Special char values
Literal symbool
Special symbol
The quote symbol
The backslash symbol
’A’
’\n’
’\’’
’\\’
’&’
’\t’
’\”’
String versus char
String char class primitive type object-reference immediate value zero, one or more… exactly one symbol “” “A” “hello” ’A’ methods operators
equals == concat < substring +
Counting words
void actionPerformed ( ActionEvent e ){ String s; int n; s = input.getText ();
}
n = s.length ();
output.setText ( “you typed ” + n + “ symbols” );output.setText ( “you typed ” + w + “ words” + “on ” + r + “ lines” );
if (s . charAt(t)==‘ ’) w++;
for ( t=0; t<s.length(); t++ )
if (s . charAt(t)==‘\n’) { r++; w++; }{
}
w = 0; r = 0;
int w, r, t;
Counting wordsvoid actionPerformed ( ActionEvent e ){ String s; int n; s = input.getText (); w=0; r=0; for (t=0; y<s.length(); t++) { if ( s.charAt(t)==‘ ’) w++; if (s.charAt(t)==‘\n’) r++; } output.setText( (w+r) + “ words on ” + + r + “ lines” );}
the actualcounting
input
output&
layout
Separate class for doingthe countingclass Counters{
}
int r, w;Counters(){ r=0; w=0;}void check (String s){ for (t=0; t<s.length; t++) ....r++....w++....}
String toString ( ){ return (w+r) + “ words on ” + r + “ lines”;}
Using the new class
void actionPerformed(ActionEvent e){
}
Counters c;c = new Counters();c . check ( input.getText() );output . setText ( c.toString() );
Counting digitsclass Counters{ int t0, t1, t2, t3, t4, t5, t6, t7, t8, t9;
Counters(){ t0=0; t1=0; t2=0; t3=0; t4=0; t5=0; t6=0; t7=0; t8=0; t9=0;}void check (String s){ for (t=0; t<s.length; t++) { if (s.charAt(t)==‘0’) t0++; if (s.charAt(t)==‘1’) t1++; if (s.charAt(t)==‘2’) t2++; if (s.charAt(t)==‘3’) t3++; if (s.charAt(t)==‘4’) t4++; if (s.charAt(t)==‘5’) t5++; if (s.charAt(t)==‘6’) t6++; if (s.charAt(t)==‘7’) t7++;
OK, OK,I got it...
Arrays
Array: many numbered variables
table
0
1
2
3
4
length5
int [ ] table;
new int [5];
table =
declaration ofthe array
creation ofthe object
Use of an array
all the variables can be actually used:
table
0
1
2
3
4
length5table [2] = 37;
x = table [2] + 5;
37
x 42
if (table.length<10) ...
table.length = 10;
but you cannot changethe length
Use of an array
variable as an index into the array
table
0
1
2
3
4
length5table [0] = 0;table [1] = 0;table [2] = 0;table [3] = 0;table [4] = 0;
0
0
0
0
0
table [t] = 0;for (t=0; t<5; t++)
Array as a parameter
table
0
1
2
3
4
length5
12
95
11
23
15
int smallest ( int [ ] table ){
}
int result;
return result;
if (table [t] < result)result = table [t];
for (t=0; t<table.length; t++)
int t;
result =table [0];
Application:character counter
user types some text...
presses the button...
and the programdetermines all
character frequencies
Program structure
public class Text extends Applet implements ActionListener{ TextArea input, output; Button count;
public void init (){ input = new TextArea( 5, 30);
output = new TextArea(28, 20);count = new Button(“count characters”);output . setEditable (false);this.add(input); this.add(count); this.add(output);count.setActionListener (this);
}
Program structure
public class Text extends Applet implements ActionListener{ TextArea input, output; Button count;
public void actionPerformed(ActionEvent e){
Counters table;table = new Counters ( );
table . check ( input.getText() );
}
output . setText ( table.toString() );
}
Class Counters
public class Counters{
int [ ] tab;int total;
public Counters ( ) { ... }public void check (String s){ ... }public String toString ( ) { ... }
private void check (char c){ ... }
}
class design:what is ...
& what does ...& how?
Class Counterspublic class Counters{ int [ ] tab; int total;
public Counters ( ){
}
tab = new int [26];
}
for (t=0; t<26; t++) tab [t] = 0;
int t;
public void check (String s){
}check (s.charAt(t));
for (t=0; t<s.length(); t++)int t;
Class Counterspublic class counters{ int [ ] tab; int total;
public void check (char c){
}
tab [ ] ++;total++;
}
if (c>=‘A’ && c<=‘Z’){
}
c - ‘A’
if (c>=‘a’ && c<=‘z’){ tab [ c - ‘a’ ] ++; total++;}
t + “:” + tab[t] + “times\n” ;
Class Counterspublic class Counters{ int [ ] tab; int total;
public String toString( ){
}}
String result;
return result;
result = “”;
result +=for (t=0; t<26; t++)
int t;
result += “total:” + total;
(t+ ‘A’) + “:” + tab[t] + “times\n” ;
(char) (t+ ‘A’) + “:” + tab[t] + “times\n” ;