48
OOP in Java : © W. Milner 2005 : OOP in Java

OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

Embed Size (px)

Citation preview

Page 1: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 1

OOP in Java

Page 2: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 2

Course outline

1. Getting started, primitive data types and control structures

2. Classes and objects3. Extending classes4. Using some standard packages5. OOP revisited

Sessions 1 to 3 introduce and sketch out the ideas of OOP. Session 5 deals with these ideas in closer detail.

Page 3: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 3

Recommended text

The Java Programming Language Third Edition by Arnold, Gosling and Holmes – Addison Wesley

Gosling created the Java language In the spirit of The C Programming Language

by K & R, and the C++ Programming Language by Stroustrup

If you’ve never written a computer program before, it won’t make much sense

Page 4: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 4

What you need to know already

What compiling and iterpreting mean Some knowledge of C

– Much Java syntax is like C, so– We’ll say ‘it’s like C except that..’

Page 5: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 5

Getting started

Just follow these steps – explanations later Look at java.sun.com for what is available You need J2SE = Java 2 Standard Edition Download and install the JDK – currently 5.0

Update 5 This will install software needed in

C:\Program files\java Create a directory where you will save your

Java programs – call the folder JavaProgs

Page 6: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 6

Keeping Going

Start NotePad and enter the program on the next slide.

Save it with the filename “First.java” – must be this name. Put quotes around it – make sure Notepad does not put .txt on the end.

Note CAPITAL F. Save it in your JavaProgs folder:

Page 7: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 7

The first program

public class First{public static void main(String[] args)

{System.out.println("Hello world");}

}

Page 8: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 8

Then..

Switch to the command prompt (Start Programs Accessories Command Prompt) and navigate to your JavaProgs folder

Use cd to change directory. Cd.. Moves ‘up’ a level.

You should have something like:

Page 9: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 9

Compile it

The compiler is called javac. You’ll need to include the path to it, so type in:

After this, get this line back using the up and down arrow keys.

Then run it like this:

Page 10: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 10

Explanations..

All Java source code files are called Something.java

You give this to the javac compiler This produces a file called Something.class This is in bytecode This can be interpreted by the java interpreter

Page 11: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 11

More explanations

Each source code file defines a class The name of the class it defines (First in our

case) must match the filename – hence First.java

This is compiled to a bytecode file named First.class

Java is case-sensitive (like C) Classes should start with a capital letter. So the file must be called First.java and not

first.java

Page 12: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 12

Exercise

Change the file First.java so it defines a class called Second – and save it as Second.java

Change it so it outputs ‘my second program’ instead of ‘Hello world’

Compile and run it.

Page 13: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 13

Features of Java

Java is a general purpose high level language Core Java is well-defined and stable Versions are useful in many situations –

desktop, server, embedded, mobile etc Java is a trademark of Sun Microsystems Java is cross -platform

Page 14: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 14

More features

Java is a pure object-oriented language. No functions, no global variables Unlike C++, which is C with objects Java is designed to make it hard to write

programs which will crash No pointers Compiler will not compile doubtful code Programmer must write code that ‘catches

exceptions’ Run-time checks eg array bounds exceptions Slower than C or C++ (not much), but less

chance of crash

Page 15: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 15

Types

Recall data type from C – int, char double etc Java has 2 kinds of types:

Primitive typesReference types

Page 16: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 16

Primitive types

These are simple types like char, double, int Similar to C Main difference – the sizes of these types are

defined eg an int is 4 bytes Each hardware platform has its own 'virtual

machine' Which all look the same So can all have the same data sizes All chars use UNICODE character set - so

characters are 2 bytes long

Page 17: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 17

Reference types

Reference type variables are objects Objects belong to classes Objects made by a constructor

Page 18: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 18

Primitive types first

We will look at primitive types first and control structures (loops and ifs) Then look at classes and objects

Page 19: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 19

Program format

public class Testing{public static void main(String[] args)

{// find the area of a circle..double radius = 5.0;double area;area = 3.1416 * radius * radius;System.out.println("Area = " + area);}

}

Use this format to start withIn file Testing.javaCode goes hereExplain rest later

Page 20: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 20

Variables - declaring and assigning

// starts a line comment double area declares a variable called area of type double double radius = 5.0; declares and initializes a variable variables can be declared anywhere in a block { } statements end in ; like C and C++

public class Testing{public static void main(String[] args)

{// find the area of a circle..double radius = 5.0;double area;area = 3.1416 * radius * radius;System.out.println("Area = " + area);}

}

Page 21: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 21

Console output

System.out.println("Area = " + area); This takes a single string argument – but.. The + causes area to be converted to the

equivalent string, and concatenated with the left hand operand so we get "Area = 5.72" or whatever System.out.print stays on same line

Page 22: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 22

Primitive data types - numericName Range Size

byte -27 to 27-1 (-128 to +127) 8 bits

short -215 to 215-1 ( ± 32 000 ) 16 bits

int -231 to 231-1 ( ± 2 500 million ) 32 bits

long -263 to 263-1 (very big!!) 64 bits

float about 1038, 6/ 7 sig digits 32 bits

double 10308, 14/ 15 sig digits 64 bits

Java data type sizes are platform independent

All are signed

Top four are integer, bottom two are floating point

Variables of these types declared like

short a,b,c; or initialised when declared

double x = 1.502;

Page 23: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 23

Numeric data types

Can get overflow eg– int i = 64000;– int n = i * i ;

Specify type of constant like– x = 1000L; // defaults to integer– f = 1.0F; // force float - defaults to double– x = 0x1FF; // hex

Operators + - * / % is mod = remainder eg 13 % 4 is 1 Short cut – same as C

+= x+=8; same as x = x + 8;-= x-=8; same as x = x - 8;*= x*=8; same as x = x * 8;/= x/=8; same as x = x / 8;%= x%=8; same as x = x % 8;

Page 24: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 24

Overflow Exercise

Use code to produce overflow as in the previous slide

Find out what happens when you compile/run it.

Page 25: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 25

Two types of division

float f = 1.0 / 2.0; // floating point int i = 1 / 2; // i is 0 if both operands are integer, / is integer version - it

gives the quotient and discards the remainder So / is overloaded – different versions, same name

Page 26: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 26

Increment and decrement

x++; is the same as x = x + 1; y--; is the same as y = y - 1; post-increment is like

a = b++;which first assigns b to athen increments b

pre-increment isa = ++b;which first increments bthen assigns the new value to a

Page 27: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 27

Type casts

Assigning a small type to a larger type is no problem eg

int i;long x;i = 32;x = i; OK because x more bits than i

But reverse gives ‘possible loss of precision’ eg int i;

long x;x = 32;i = x; // gives compile error

Problem solved by a type casttype cast iei = (int) x;

Page 28: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 28

Type cast exercise

Try out int i;

long x;x = 32;i = x;

In a program. Fix it as in the previous slide

Page 29: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 29

Char type char is for a single character, like char c = ‘A’; note single quotes c++; makes c = ‘B’ Strings are different - see later Java uses UnicodeUnicode not ASCII - 16

bits per character eg

import java.applet.*;import java.awt.*;

public class TestApplet extends Applet{public void paint(Graphics g) {

char c; Font f = new Font("Arial Unicode MS",Font.PLAIN,20); g.setFont(f);

c = '\u098a'; // Unicode constant g.drawString("Some Bengali: " + c,10,30 ); }}

Page 30: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 30

boolean type

If a variable is declared to be boolean, it is restricted to 2 values - true and false

boolean result; result = true;

result = ( x > y );result is true if x is greater than y

also < <= >= == != == not the same as =

&& and || or ! not result = ( x > y ) && ( y < 5 );

result is true if x is greater than y and y is less than 5

&& and || are short-cut operators

Page 31: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 31

bitwise operators

& is bitwise AND (like both)| is bitwise OR (like either )^ is XOR (like not equal)~ is NOT

eg if x = 9 1001and y = 10 1010

x & y is 8 1000 x | y is 11 1011 x ^ y is 3 0011 ~ 0xFFFFFFFE is 1 inverting 11111111110

Page 32: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 32

bit shift operators

>> is shift righteg if x = 7 or in binary 0000 0111x >> 1 is 0000 0011

<< is shift left sox << 1 is 0000 1110 = 14

Page 33: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 33

Bit shift exercise

Try out this code:int i = 6;System.out.println(i&1);i>>=1;System.out.println(i&1);i>>=1;System.out.println(i&1); Explain what you get

Page 34: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 34

precedence

2 * 3 + 4 is 10 not 142*(3+4) is 14Highest ++ --

* / %+ -< <= > >=== !=&&||

Lowest = += -= *= /= %=Use brackets when in doubt

Page 35: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 35

Control - if

for exampleif ( x== 5 )

{y = 2;a++;}

elsec++;

round brackets around boolean expression indentation no then as in Visual Basic block { } around several steps to do no block if just one step -

if (x<4)a=4;

else can be omitted if not needed

Page 36: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 36

if example - validation

for exampleif ( ( age>0 ) && ( age < 130 ) )

System.out.println(‘age is valid’);else

{System.out.println(‘age is invalid’);..code to deal with error..}

beware ofif ( x==5 );

y = 2;

Page 37: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 37

switch - I

used where many alternative actions are possible example -

switch (y){case 5: a = 7;case 9: b = 3;case 4: a = 8;default: z = 2;}

y can be expression (like x + 4) but must be integral the 5, 9, 4 etc must be constants default is optional

Page 38: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 38

switch - II

the action ‘falls through’ - when one case is triggered, all the following options execute to the end of the switch

so often combine with breakbreak - example -switch (y)

{case 5: a = 7; break;case 9: b = 3; break;case 4: a = 8; break;}

include final break - not essential but good practice, since if add further option do not need to go back and add break to previous

Page 39: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 39

Conditional operator ? ;

examplex = ( y > 4 ) ? 7 : 3;if y is greater than 4, x becomes 7, and otherwise, it becomes 3

in generala ? b : cb is evaluated if a is true, c if it is not

exampleint x =9, y = 10 , a;a = (x > 9) ? x++ : y++ ;

after this a = 10, y is 11, x is still 9

Page 40: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 40

loops - while

loops repeat blocks of code - called iteration example - output the numbers 3, 6, 9, ... 99

x = 3;while ( x<102 ) {

System.out.println( x ); x += 3; }

in general,while (boolean expression)

statement or block to repeat need to initialise variables may loop zero times if false first time use indentation

Page 41: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 41

loops - do while

example - output the numbers 3, 6, 9, ... 99x = 3;do {

System.out.println( x ); x += 3; } while ( x<102 )

in general,do statement or block to repeat while (boolean expression)

unlike a while, it will execute the loop at least once

Page 42: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 42

loops - for

example - output the numbers 3, 6, 9, ... 99for ( x = 3; x<102; x+=3 ) System.out.println(x);

in generalfor ( <initialisation> ; <loop while true>; <change every time> )

< statement or block to repeat > may loop zero times add up the integers 1 + 2 + 3 + ...100

int t = 0;int x;for ( x = 1; x<101; x++)

t += x;System.out.println( t );

Page 43: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 43

loops - for - II

can use statement liststatement list, likeint t;int x;for ( x = 1, t = 0; x<101; x++)

t+=x;System.out.println(t);

can omit any part, (retain separating ; ) likeint t = 0;int x = 1;for ( ; x<101; x++)

t+=x;System.out.println(t);

for (; ; ) loops forever

Page 44: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 44

can declare variable in for, likeint t = 0;for ( int x = 1; x<101; x++)

t+=x;System.out.println(t);in this case the scope of the variable is limited to the for statement

loops - for - III

do not do this -

for ( int x = 1; x<101; x++);t+=x;

Page 45: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 45

Arrays - I

An array is a set of boxes (elementselements) each labelled with a number (indexindex)

Arrays are declared and created asint [ ] numbers = new int [ 100 ];which makes an array of 100 integers called numbers

or do it in 2 stepsint [ ] numbers; //declare itnumbers = new int [ 100 ]; // create it

or initialise itint [ ] numbers = { 4, 2, 1, 3, 5 };

can have arrays of anything

Page 46: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 46

Arrays - II

Array elements referred to likenumbers [4] = 18;

Multi-dimensional arrays created and used likeint [ ] [ ] table = new int [5] [10];

table[3][4]=7; Array element numbering starts at 0 so

int [ ] numbers = new int [ 100 ];creates 100 elements, from numbers[0] to numbers[99]

array bounds are checked at compile time and run time

Page 47: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 47

Arr

ays

- so

rtin

g int [ ] numbers = new int [5];

//.. put some numbers in the array, then...sort them

// a bubble sort.. for ( int i = 0; i < 5; i++ )

for ( int j = 0; j < 4-i; j++ ) if ( numbers[ j ] > numbers[ j+1] ) { // swap them int temp;

temp = numbers[ j ];numbers[ j ] = numbers[ j+1 ];numbers[ j+1 ] = temp;};

Page 48: OOP in Java : © W. Milner 2005 : Slide 1 OOP in Java

OOP in Java : © W. Milner 2005 : Slide 48

Array exercise

Declare an array of 100 doubles Fill the array with random numbers (use

Math.random(); ) Print them out