You are on page 1of 184

1/10

Lecture 1a: Java Introduction



Big companies like IBM are embracing Java far more than most people realize. Half of
IBM is busy recoding billions of lines of software to Java. The other half is working to
make Java run well on all platforms, and great on all future platforms.
PBS technology commentator Robert X. Cringely
You'll also become a Java programmer with a lot of potential. Welcome to Java World!

J avas Lineage
Java is related to C++, which is a direct descendent of C. Much of the
character of Java is inherited from these two languages.
From C, Java derives its syntax.
Many of Javas object-oriented features were influenced by C++.
The J ava Buzzwords

No discussion of the genesis of Java is complete without a look at the Java buzzwords.
Simple
Secure
Portable
Object-oriented
Robust
Multithreaded
Architecture-neutral
Interpreted
High performance
Distributed
Dynamic
2/10
Java - Characteristics
Uses C/C++ basic syntax and basic data types -int, char, float, double, long,
short, byte etc.
Uses standard C/C++ control structures
Pure OO language
No stand alone functions -All code is part of a class
No explicit pointers - uses references
Uses garbage collection
Java is strongly typed
Java is normally compiled to a bytecode ;Java bytecode is a machine language
for an abstract machine
Each platform (or browser) that runs Java has a Java Virtual Machine (JVM or
sometimes VM) . The JVM executes Java bytecodes

Java - The Platform
Java has a large API (application programming interface) covering a wide
range of areas The following list of Java APIs and applications from Sun
show the range of applications of Java . For reference
http://java.sun.com/products/index.html
Java Foundation Classes (JFC) - GUI
JDBC Database Access
JavaBeans - componentware
Java Web Server
EmbeddedJava - Java on embedded devices


3/10
JAVA IDE
Using JDK you can compile and run java program from command line.
o c:> javac HelloWorld. java - compiling here and it will produce
HelloWorld.class i.e. bytecode.
o c:>java HelloWorld - It runs java byte code on native machine

Creating, Compiling, Debugging and Execution for these four steps JDK is not
user friendly. IDE is provided for that. A list of IDEs are:
o Eclipse - from IBM
o Netbeans.



An Example HelloWorld
/**
This is my first java program
*/

publ i c cl ass Hel l oWor l dExampl e
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
Syst em. out . pr i nt l n( " Hel l o Wor l d" ) ;
}
}

Java Source Code Naming Conventions
All java source file should end in .java
Each .java file can contain only one public class
The name of the file should be the name of the public class plus ".java"
Do not use abbreviations in the name of the class
If the class name contains multiple words then capitalize the first letter of each
word ex. HelloWorld.java



UIU Lecture 1a, CSI 211
4/10
CLASSPATH
Java uses the environment variable CLASSPATH to locate class libraries
.class files those needed to compile or run the program it searches from
CLASSPATH
By default class path consists only the current directory but you can provide them
in classpath option of javac or include directories in CLASSPATH environment
variables.
Example classpath = . ; c:\java\lib; c:\csi211\lab

Some Basic Java Syntax
Java Comments
/* Standard C comment works
*/

// C++ comment works

/** Special comment for documentation java comments
*/

cl ass Synt ax
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
i nt aVar i abl e = 5;
doubl e aFl oat = 5. 8;

i f ( aVar i abl e < aFl oat )
Syst em. out . pr i nt l n( " Tr ue" ) ;

i nt b = 10; / / Thi s i s l egal i n J ava
char c;
c = ' a' ;
}
}










5/10
Java Program Style and Layout

Three different indentation styles you can use
You can pick a reasonable indentation style and use it consistently in your
programs

Style#1

cl ass Synt ax { / / br ace st ar t s f r omher e
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) {
i nt aVar i abl e = 5;
i f ( aVar i abl e < aFl oat )
Syst em. out . pr i nt l n( " Tr ue" ) ;
}
}

St yl e #2

cl ass Synt ax
{ / / br ace st ar t s
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
i nt aVar i abl e = 5;
i f ( aVar i abl e < aFl oat )
Syst em. out . pr i nt l n( " Tr ue" ) ;
}
}

St yl e#3

cl ass Synt ax
{/ / br ace st ar t s
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
i nt aVar i abl e = 5;
i f ( aVar i abl e < aFl oat )
Syst em. out . pr i nt l n( " Tr ue" ) ;
}
}

Naming conventions

Class Naming Uses Capitalized word(s) i.e. Title case

Examples:-
HelloWorld, MyList, StudentMark

Wrong:
helloWorld, HW (do not use abbreviation)



6/10
Variable and function names

starts with a lowercase letter and after that use Title case

Examples:-
variableAndFunctionNames
aFloat, studentName

Names of constants

All are capital letters and separated by underscore. Example is
NAMES_OF_CONSTANTS

Boolean

true, false act like keywords but are boolean constants

public class Bool eanTest {
public static void mai n( St r i ng ar gs[ ] ) {
boolean f l ag = 2 > 3;
if ( f l ag && true)
Syst em. out. pr i nt l n( " Tr ue" ) ;
else
Syst em. out. pr i nt l n( " Fal se" ) ;
}
}

Input and Output
Standard Java Output

System.out is standard out in Java
System.err is error out in Java

cl ass Out put
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
/ / St andar d out
Syst em. out . pr i nt ( " Pr i nt s, but no newl i ne" ) ;
Syst em. out . pr i nt l n( " Pr i nt s, adds pl at f or ms newl i ne at end" ) ;
doubl e t est = 4. 6;
Syst em. out . pr i nt l n( " You can use " + " t he pl us oper at or on "
+ t est + " St r i ng mi xed wi t h number s" ) ;

Syst em. er r . pr i nt l n( " St andar d er r or out put " ) ;
}
}
7/10
Output

Pr i nt s, but no l i nef eed Pr i nt s, adds l i nef eed at end
You can use t he pl us oper at or on 4. 6 St r i ng mi xed wi t h number s
St andar d er r or out put

Standard Java Input

Java assumes that you will be using a GUI for input from the user Hence there is
no "simple" way to read input from a user
Scanner class is in jdk 1.5

package l ect ur e01;

import j ava. ut i l . Scanner ;

public class Test I nput {
public static void mai n( St r i ng[ ] ar gs ) {

Scanner scanner = new Scanner ( Syst em. in) ;

Syst em. out. pr i nt ( " Wr i t e your name: " ) ;
St r i ng user Name = scanner . next Li ne( ) ;
Syst em. out. pr i nt l n( " Your name i s : " + user Name) ;
}
}

Output
Wr i t e your name: Monzur ur Rahman
Your name i s : Monzur ur RahmanYou t yped: 34

Basic Data Types

cl ass Pr i mi t i veTypes
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
/ / I nt egr al Types
byt e aByt eVar i abl e; / / 8- bi t s
shor t aShor t Var i abl e; / / 16- bi t s
i nt aI nt Var i abl e; / / 32- bi t s
l ong aLongVar i abl e; / / 64- bi t s
/ / Fl oat i ng- Poi nt Types
f l oat aFl oat Var i abl e; / / 32- bi t I EEE 754 f l oat
doubl e aDoubl eVar i abl e; / / 64- bi t I EEE 754 f l oat
/ / Char act er Type
char aChar Var i abl e; / / al ways 16- bi t Uni code
/ / Bool ean Types
bool ean aBool eanVar i abl e; / / t r ue or f al se
}
}
8/10

Operations on Primitive Types

Equality = !=
Relational < <= > >=
Unary + -
Arithmetic + - * / %
Pre, postfix increment/decrement ++ --
Shift << >> >>>
Unary Bitwise logical negation ~
Binary Bitwise logical operators & | ^




cl ass Oper at i ons
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
i nt a = 2;
i nt b = +4;
i nt c = a + b;
i f ( b > a )
Syst em. out . pr i nt l n( " b i s l ar ger " ) ;
el se
Syst em. out . pr i nt l n( " a i s l ar ger " ) ;
Syst em. out . pr i nt l n( a << 1) ; / / Shi f t l ef t : 4
Syst em. out . pr i nt l n( a >> 1) ; / / Shi f t r i ght : 1
Syst em. out . pr i nt l n( ~a ) ; / / bi t wi se negat i on: - 3
Syst em. out . pr i nt l n( a | b) ; / / bi t wi se OR: 6
Syst em. out . pr i nt l n( a ^ b) ; / / bi t wi se XOR: 6
Syst em. out . pr i nt l n( a & b) ; / / bi t wi se AND: 0
}
}


9/10
NaN, +, -

Zero divide with floating-point results in +, -

Overflow results in either +, -.

Underflow results in zero.

An operation that has no mathematically definite result produces NaN - Not a
Number

NaN is not equal to any number, including another NaN

cl ass NaN
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
f l oat si ze = 0;
f l oat aver age = 10 / si ze;
f l oat i nf i ni t y = 1. 40e38f * 1. 40e38f ;
Syst em. out . pr i nt l n( aver age ) ; / / Pr i nt s I nf i ni t y
Syst em. out . pr i nt l n( i nf i ni t y ) ; / / Pr i nt s I nf i ni t y
}
}



Casting

cl ass Cast i ng
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
i nt anI nt = 5;
f l oat aFl oat = 5. 8f ;
aFl oat = anI nt ; / / I mpl i ci t cast s up ar e ok
anI nt = aFl oat ; / / Compi l e er r or ,
/ / must expl i ci t l y cast down
anI nt = ( i nt ) aFl oat ;
f l oat er r or = 5. 8; / / Compi l e er r or , 5. 8 i s doubl e
f l oat wor ks = ( f l oat ) 5. 8;
char c = ( char ) aFl oat ;
doubl e aDoubl e = 12D;
doubl e bDoubl e = anI nt + aDoubl e; / / anI nt i s cast upt o doubl e,
i nt noWay = 5 / 0; / / Compi l e er r or , compi l er det ect s
/ / zer o di vi de
i nt zer o = 0;
i nt t r oubl e = 5 / zer o; / / Some compi l er s may gi ve er r or her e
i nt not Zer oYet ;
not Zer oYet = 0;
10/10
t r oubl e = 5 / not Zer oYet ; / / No compi l e er r or !
}
}


Ints and Booleans are Different

cl ass UseBool ean
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
i f ( ( 5 > 4 ) == t r ue )
Syst em. out . pr i nt l n( " J ava' s expl i ci t compar e " ) ;
i f ( 5 > 4 )
Syst em. out . pr i nt l n( " J ava' s i mpl i ci t compar e " ) ;
i f ( ( 5 > 4 ) ! = 0 ) / / Compi l e er r or
Syst em. out . pr i nt l n( " C way does not wor k" ) ;
bool ean cant Cast Fr omI nt ToBool ean = ( bool ean) 0;
/ / compi l e er r or
i nt x = 10;
i nt y = 5;
i f ( x = y ) / / Compi l e er r or
Syst em. out . pr i nt l n( " Thi s does not wor k i n J ava " ) ;
}
}


*************** End of Lecture 1a **************
1/13
United International University

Course: CSI 211
Course Title: Object Oriented Programming
Lecture 1b: Array and Control Structure

Arrays
Major differences with C/C++arrays:
J ava arrays are references
J ava arrays know their size
J ava checks the bounds of an array when accessed
J ava multidimensional arrays need not be rectangular
J ava array elements are initialized
Exampl e 1: )

publ i c cl ass Si mpl eRef er enceExampl e
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
/ / Ref er ence al l ocat ed, no ar r ay space al l ocat ed
f l oat [ ] sampl eAr r ay;
/ / al l ocat e ar r ay l ocat i ons on heap
sampl eAr r ay = new f l oat [ 12 ] ;
/ / I ndexi ng st ar t s at 0 l i ke C/ C++
sampl eAr r ay[ 0 ] = 3. 2F;
i nt [ ] i nt eger Ar r ay = new i nt [ 3 ] ;

/ / Ref er ence r ef er s t o new ar r ay.
/ / Ol d ar r ay avai l abl e f or gar bage col l ect i on
sampl eAr r ay = new f l oat [ 2 ] ;
}
}

2/13
Exampl e 2: )

publ i c cl ass Ar r ayExampl es
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
/ / Two l ocat i ons t o pl ace [ ]
i nt i nt eger Ar r ay[ ] ;
i nt [ ] al i as;
i nt eger Ar r ay = new i nt [ 10 ] ; / / I ndexed f r om0 t o 9
/ / Not e use of . l engt h t o get ar r ay si ze
f or ( i nt i ndex = 0; i ndex < i nt eger Ar r ay. l engt h; i ndex++ )
i nt eger Ar r ay[ i ndex ] = 5;
al i as = i nt eger Ar r ay; / / Ar r ays ar e r ef er ences
al i as[ 3 ] = 10;
Syst em. out . pr i nt l n( i nt eger Ar r ay[ 3 ] ) ; / / Pr i nt s 10

i nt eger Ar r ay = new i nt [ 8 ] ;
Syst em. out . pr i nt l n( i nt eger Ar r ay[ 3 ] ) ; / / Pr i nt s 0, Why?
Syst em. out . pr i nt l n( al i as[ 3 ] ) ; / / Pr i nt s 10
Syst em. out . pr i nt l n( i nt eger Ar r ay ) ; / / Pr i nt s [ I @5e300868
}
}




Arrays, References, Memory Leaks
Arrays are references!
Garbage collection reclaims arrays that can not be accessed!
References are initialized to null
When done with a reference set it to null

publ i c cl assAr r ayExampl es
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
i nt [ ] i nt eger Ar r ay = new i nt [ 4 ] ;
i nt eger Ar r ay[ 1 ] = 12
i nt eger Ar r ay = new i nt [ 2 ] ; / / Memor y Leak - No!
i nt eger Ar r ay[ 1 ] = 5;
i nt [ ] al i asFor Ar r ay = i nt eger Ar r ay;
al i asFor Ar r ay[ 1 ] = 10;
Syst em. out . pr i nt l n( i nt eger Ar r ay[ 1 ] ) ; / / Pr i nt s 10
}
}
3/13
HEAP ALLOCATION

i nt [ ] i nt eger Ar r ay = new i nt [ 4 ] ;


i nt eger Ar r ay[ 1 ] = 12


i nt eger Ar r ay = new i nt [ 2 ] ; / / Memor y Leak - No!


i nt eger Ar r ay[ 1 ] = 5;

i nt [ ] al i asFor Ar r ay = i nt eger Ar r ay;


al i asFor Ar r ay[ 1 ] = 10;







Memory Problems in C/C++


Memory Leaks

Memory that program has allocated but can no longer access
int* trouble =new int( 5 );
trouble =new int( 8 );






4/13
Dangling References

Two or more pointers point to the same memory on the heap
Using one of the pointers the memory is deallocated
Second pointer can still access the memory
Estimates are that up to 40% of development time in C/C++are spent dealing
with these two problems


Java Solution

No pointers
No explicit deallocation of memory
When memory can no longer be accessed, garbage collection eventually
reclaims the memory



J ava' s sol ut i on i s mor e dynami c, f l exi bl e, and saf er t han C/ C++



Array Bounds and Initial Values

Any access of an array element is check at runtime to insure the element index is
valid

The example below shows what happens when accessing an illegal index.
The lower index of an array is always zero
All array elements are given an initial value
The actual value given depend on the type

5/13
publ i c cl ass BoundsAndI ni t i al Val ueExampl e
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
i nt [ ] dat a = new i nt [ 2] ;

Syst em. out . pr i nt l n( " Dat a[ 1] = " + dat a[ 1] ) ;
dat a[ 12] = 2;
Syst em. out . pr i nt l n( " Af t er assi gnment " ) ;
}
}
Output
Dat a[ 1] = 0
j ava. l ang. Ar r ayI ndexOut Of BoundsExcept i on
at
BoundsAndI ni t i al Val ueExampl e. mai n( BoundsAndI ni t i al Val ueExampl e. j ava: 9)


Array Initializer's
One can initialize arrays to a list of values
The syntax is slightly different for declaration statements and assignments
There is no way to indicate repeated values in the initializer
publ i c cl ass I ni t i al i zi ngAr r ays
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
/ / Shor t Decl ar at i on synt ax
i nt [ ] odds = {1, 3, 5, 7, 9 };
char [ ] vowel s = { ' a' , ' e' , ' i ' , ' o' , ' u' };
St r i ng[ ] names;
/ / Assi gnment synt ax - new i n J DK 1. 1. x
names = new St r i ng[ ] { " Sam" , " Sal l y" , " Pet e" };
/ / Can use l onger synt ax i n decl ar at i ons
char [ ] abc = new char [ ] { ' a' , ' b' , ' c' };
/ / You can not use shor t synt ax i n assi gnment s
doubl e[ ] t r oubl e;

t r oubl e = { 1. 2, 2. 3, 5. 4 }; / / Compi l er Er r or
}
}

6/13
Multidimensional Arrays
publ i c cl ass Mul t i di mensi onal Ar r ayExampl e
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
i nt [ ] [ ] squar eAr r ay = new i nt [ 10 ] [ 20 ] ;
squar eAr r ay[ 2 ] [ 5 ] = 25;
i nt [ ] [ ] [ ] t hr eeDAr r ay = new i nt [ 10 ] [ 20 ] [ 5 ] ;
i nt [ ] [ ] t r i angul ar Ar r ay;
t r i angul ar Ar r ay = new i nt [ 30 ] [ ] ;
/ / Al l ocat e r ows of di f f er ent l engt h!
f or ( i nt r ow = 0; r ow < t r i angul ar Ar r ay. l engt h; r ow ++ )
t r i angul ar Ar r ay [ r ow ] = new i nt [ r ow ] ;
/ / Fi l l ar r ay l ocat i ons
f or ( i nt r ow = 0; r ow < t r i angul ar Ar r ay. l engt h; r ow ++ )
f or ( i nt col = 0; col < t r i angul ar Ar r ay[ r ow ] . l engt h; col ++
)
t r i angul ar Ar r ay[ r ow ] [ col ] = 10;
/ / I ni t i al i zer s f or mul t i di mensi onal ar r ays,
/ / not e t he di f f er ent si ze r ows
i nt [ ] [ ] oddShape = {
{ 1 , 2, 3 } ,
{ 1, 2 },
{ 4, 5, 6, 7 }
};
}
}

New Array Operation Example

i mpor t j ava. ut i l . Ar r ays;
publ i c cl ass NewAr r ayOper at i ons
{
publ i c st at i c voi d mai n( St r i ng[ ] ar gs )
{
i nt [ ] l i st = { 9, 2, 5, 7, 1 };

/ / Sor t s usi ng f ancy qui cksor t
Ar r ays. sor t ( l i st ) ;

/ / i f not f ound, t hen r et ur n - 1
i nt f oundI ndex = Ar r ays. bi nar ySear ch( l i st , 7 ) ;

Syst em. out . pr i nt l n( " Found 7 at : " + f oundI ndex ) ;

i nt [ ] ones = new i nt [ 12 ] ;

/ / Fi l l ar r ay wi t h val ue 1
Ar r ays. f i l l ( ones, 1 ) ;
Syst em. out . pr i nt l n( " One: " + ones[ 10] ) ;
}
}
7/13
Output
Found 7 at : 3
One: 1

Strings
publ i c cl ass St r i ngExampl e
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
St r i ng f i r st Name = " Roger " ;
St r i ng l ast Name = " Whi t ney " ;
St r i ng f ul l Name = f i r st Name + l ast Name;
Syst em. out . pr i nt l n( f ul l Name ) ;
f i r st Name = f i r st Name. t oLower Case( ) ;
l ast Name = l ast Name. t oUpper Case( ) ;
Syst em. out . pr i nt l n( f i r st Name ) ;
f i r st Name = f i r st Name. t r i m( ) ; / / t r i ml eadi ng, t r ai l i ng
l ast Name = l ast Name. t r i m( ) ; / / whi t e space
l ast Name = l ast Name. r epl ace( ' I ' , ' a' ) ;
Syst em. out . pr i nt l n( f i r st Name + l ast Name ) ;
St r i ng f l oat AsSt r i ng = St r i ng. val ueOf ( 13. 4e+5f ) ;
Syst em. out . pr i nt l n( f l oat AsSt r i ng ) ;
}
}

Output
Roger Whi t ney
r oger
r oger WHaTNEY
1. 34e+06


String Operations
charAt(int) replace(char,char)
compareTo(String) startsWith(String)
concat(String) substring(int,int)
equals(Object) toUpperCase()
equalsIgnoreCase(String) trim()
length() valueOf(double)

8/13
String comparison == and Strings

publ i c cl ass St r i ngTest
{
publ i c st at i c voi d mai n( St r i ng[ ] ar gs )
{
St r i ng me = " Roger " ;

i f ( me == " Roger " )
Syst em. out . pr i nt l n( " Yes, I amme" ) ;
el se
Syst em. out . pr i nt l n( " No, I amnot me?" ) ;

St r i ng shor t Name = me. subst r i ng( 0, 3 ) ;
Syst em. out . pr i nt l n( shor t Name ) ;

i f ( shor t Name == " Rog" )
Syst em. out . pr i nt l n( " Ver y Good" ) ;
el se
Syst em. out . pr i nt l n( " Tr oubl e her e" ) ; / / How i s t hi s possi bl e?

i f ( shor t Name. equal s( " Rog" ) )
Syst em. out . pr i nt l n( " Do i t t hi s way" ) ;

}
}
Output
Yes, I am me
Rog
Trouble here
Do it this way



String variables are references to objects. The ==operator checks to see if two
string references refer to the same memory location.

i f ( me == " Roger " )
Syst em. out . pr i nt l n( " Yes, I amme" ) ;
el se
Syst em. out . pr i nt l n( " No, I amnot me?" ) ;

Compilers are allowed, but not required to store equal strings in the same memory
location. The comparison above checks to see if the two variables refer to the
same memory location. Since me was initialized with a string literal the compiler
was smart enough to store the two strings in the same location.

In the comparison:
i f ( shor t Name == " Rog" )

9/13
shortName was not initialized with a literal, so the compiler did not know to store in the
same location as "Rog". Thus this comparison is false !

The equals met hod compar es t he t wo st r i ngs t o det er mi ne i f t hey
have t he same l engt h and ar e t he same char act er by char act er .



Reading Command Line Arguments

publ i c cl ass CommandLi neExampl e
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
Syst em. out . pr i nt l n( " Ar gs l engt h: " + ar gs. l engt h ) ;
f or ( i nt k = 0; k < ar gs. l engt h; k++ )
{
Syst em. out . pr i nt l n( " Ar gument " + k + " \ t " + ar gs[ k ] ) ;
};
Fl oat secondAr gument = Fl oat . val ueOf ( ar gs[ 1 ] ) ;
Syst em. out . pr i nt l n( secondAr gument ) ;
}
}
Sample Session Running above Program
r ohan 16- > j ava CommandLi neExampl e 1 2 3 4 5
Ar gs l engt h: 5
Ar gument 0 1
Ar gument 1 2
Ar gument 2 3
Ar gument 3 4
Ar gument 4 5
2



10/13
Control Structures
Contains all the standard C/C++control structures

publ i c cl ass Cont r ol
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
i nt a = 5;
i nt b = 10;
i f ( a > b ) Syst em. out . pr i nt l n( " a i s bi gger " ) ;

i f ( a > b )
Syst em. out . pr i nt l n( " a i s bi gger " ) ;
el se
Syst em. out . pr i nt l n( " b i s bi gger " ) ;
swi t ch ( a )
{ / / Cont r ol l i ng expr essi on conver t ed t o i nt
case 4:
b++;
br eak;
case 10:
b- - ;
br eak;
def aul t : / / opt i onal
Syst em. out . pr i nt l n( " Def aul t act i on" ) ;
};
whi l e ( a < b )
{
a++;
};


One more example
f or ( i nt l oop = 0; l oop < a; l oop++ )
{
Syst em. out . pr i nt l n( a ) ;
};

Syst em. out . pr i nt l n( l oop ) ; / / Er r or , l oop does not
/ / exi st her e
do
{
Syst em. out . pr i nt l n( a- - ) ;
Syst em. out . pr i nt l n( b ) ;
}
whi l e ( a > b ) ;
i nt max = ( a > b ) ? a : b;
i f ( ( a > 5 ) && ( b < 10 ) )
Syst em. out . pr i nt l n( " Good" ) ;
a += ( a = 5 ) ;
}
}
11/13
Jump Statements
break

Exits out of a loop or switch statement
Unlabeled break exits out of the innermost loop or switch
Use labeled break to exit out of nested loops or switch

publ i c cl ass Br eakExampl e {
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) {
f or ( i nt r ow = 0; r ow < 5; r ow++ ) {
f or ( i nt col umn = 0; col umn < 4 ; col umn++ ) {
Syst em. out . pr i nt l n( r ow + " \ t " + col umn ) ;
i f ( ( ( r ow + col umn) %2 ) == 0 )
br eak;
Syst em. out . pr i nt l n( " Af t er i f " ) ;
}
};
Out er :
f or ( i nt r ow = 0; r ow < 5; r ow++ ) {
f or ( i nt col umn = 0; col umn < 4; col umn++ ) {
Syst em. out . pr i nt l n( r ow + " \ t " + col umn ) ;
i f ( ( ( r ow + col umn) %2 ) == 0 )
br eak Out er ;
Syst em. out . pr i nt l n( " Af t er i f " ) ;
}
}
}
}
Output (Read Down Column First)
0 0 3 0
1 0 After if
After if 3 1
1 1 4 0
2 0 0 0



12/13
continue

A continue statement skips to the end of the current loop's body
The loop's boolean expression is then evaluated
Methods (Functions)

What are called "functions" in C are called "methods" in J ava
Note we do not have to forward declare methods, addOne is used before it is declared

publ i c cl ass Sampl eFunct i on {
publ i c st at i c i nt subt r act One( i nt decr easeMe ) {
r et ur n decr easeMe - 1;
}
publ i c st at i c voi d mai n( St r i ng[ ] ar gs ) {
i nt st ar t Val ue = 5;
i nt smal l er = subt r act One( st ar t Val ue ) ;
i nt l ar ger = addOne( st ar t Val ue ) ;
Syst em. out . pr i nt l n( " smal l er = " + smal l er + " \ n" +
" l ar ger = " + l ar ger ) ;
}
publ i c st at i c i nt addOne( i nt i ncr easeMe ) {
r et ur n i ncr easeMe + 1;
}
}

Output
smal l er = 4
l ar ger = 6


Parameter Passing - By value only

In J ava all parameters are passed by value
The method gets a copy of the parameter
Changes to a parameter in a method are valid only in the method
publ i c cl ass Test Par amet er
{
publ i c st at i c voi d mai n( St r i ng[ ] ar gs )
{
i nt st ar t Val ue = 5;
noChange( st ar t Val ue ) ;
Syst em. out . pr i nt l n( st ar t Val ue ) ;
13/13
}
publ i c st at i c voi d noChange( i nt f i xed )
{
f i xed = f i xed + 10;
}
}
Output
5

Final variable

A final variable is a variable which has been initialized to a fixed value which
cannot be changed after initialization.
In older programming languages, a final variable would be called a constant

f i nal st at i c Poi nt or i gi n = new Poi nt ( 0, 0) ;




*************** End of Lecture 1b **************
1/11
United International University

Course: CSI 211
Course Title: Object Oriented Programming
Lecture 2a: Class and Object

Object-Oriented Programming (OOP)
C, PASCAL, BASIC Procedural language
In Procedural language data and operation are separate
J ava is OOP where approach is in term of classes
Two Paradigms in OOP
All computer programs consist of two elements: code and data. Furthermore, a
program can be conceptually organized around its code or around its data. That
is, some programs are written around what is happening and others are written
around who is being affected. These are the two paradigms that govern how
an OOP program is constructed.
Abstraction in OOP
In OOP ( Object Oriented Programming ) , Abstraction facilitates the easy
conceptualization of real world objects into the software program.
Humans manage complexity through abstraction. For example, people do not
think of a car as a set of tens of thousands of individual parts. They think of it as
a well-defined object with its own unique behavior. This abstraction allows
people to use a car to drive to the grocery store without being overwhelmed by
the complexity of the parts that form the car. They can ignore the details of how
the engine, transmission, and braking systems work. Instead they are free to
utilize the object as a whole..

The Three OOP Principles
2/11
Encapsulation
o Encapsulation is the mechanism that binds together code and the data
it manipulates, and keeps both safe from outside interference and
misuse.
o Encapsulation guarantees the integrity of the data contained in the
object.
Inheritance
o Inheritance is the process by which one object acquires the properties
of another object. This is important because it supports the concept of
hierarchical classification.
o Inheritance provides a powerful and natural mechanism for organizing
and structuring your software
o classes inherit state and behavior from their super classes.
Polymorphism
o Polymorphism (from the Greek, meaning many forms) is a feature
that allows one interface to be used for a general class of actions. The
specific action is determined by the exact nature of the situation.
o More generally, the concept of polymorphism is often expressed by
the phrase one interface, multiple methods. This means that it is
possible to design a generic interface to a group of related activities.
o Consider a stack. You might have a program that requires three types
of stacks. One stack is used for integer values, one for floating-point
values, and one for characters. The algorithm that implements each
stack is the same, even though the data being stored differs. In a non
object-oriented language, you would be required to create three
different sets of stack routines, with each set using different names.
However, because of polymorphism, in J ava you can specify a general
set of stack routines that all share the same names.
OOP Terms to describe language
Class
3/11
o A class is a blueprint or prototype from which objects are created.
Object
o An object is a software bundle of related state and behavior.
o Software objects are often used to model the real-world objects that
you find in everyday life.
Interface
o An interface is a contract between a class and the outside world. When
a class implements an interface, it promises to provide the behavior
published by that in interface.
Information Hiding
o purpose of hiding is to make inaccessible certain details that should
not affect other parts of a system.
Hierarchy
o the mapped relationships of sub- and super classes is known as a
hierarchy.
Package
o A package is a namespace for organizing classes and interfaces in a
logical manner.
o Placing your code into packages makes large software projects easier
to manage.
Basic Terms
J ava field method
C++ data member member function
Smalltalk instance variable method
C ??? function



Example of a class

o Class member refers to either a field or method
4/11

publ i c cl ass BankAccount
{
publ i c f l oat bal ance = 0. 0F; / / f i el d
publ i c voi d deposi t ( f l oat amount ) / / met hod
{
bal ance += amount ;
}
}


Java Comparisons to C++
Similar class syntax and structure
No multiple inheritance, uses interfaces instead
Functions are virtual by default
Constructors are much simpler
Destructors are not need
Packages provide separate name spaces for classes
Fields
Each object has its own copy of the fields defined in the class, that is
richStudent and poorInstructor have different values for the field balance.
In this regard, classes are like C/C++structs.
The fields in an object exist as long as the object exists

publ i c cl ass BankAccount
{
publ i c f l oat bal ance = 0. 0F;
}
publ i c cl ass RunBank
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
Syst em. out . pr i nt l n( " St ar t mai n " ) ;
BankAccount r i chSt udent = new BankAccount ( ) ;
r i chSt udent . bal ance = ( f l oat ) 100000;
BankAccount poor I nst r uct or = new BankAccount ( ) ;
poor I nst r uct or . bal ance = 5. 10F;
Syst em. out . pr i nt l n( " St udent Bal ance: " +
r i chSt udent . bal ance ) ;
Syst em. out . pr i nt l n( " Pr of Bal ance: " + poor I nst r uct or . bal ance ) ;
}
}
5/11
Output
St ar t mai n
St udent Bal ance: 100000
Pr of Bal ance: 5. 1


Methods
publ i c cl ass BankAccount
{
publ i c f l oat bal ance = 0. 0F;
publ i c voi d deposi t ( f l oat amount )
{
bal ance += amount ;
}
publ i c St r i ng t oSt r i ng( )
{
r et ur n " Account Bal ance: " + bal ance;
}
}
publ i c cl ass RunBank
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
BankAccount r i chSt udent = new BankAccount ( ) ;
BankAccount poor I nst r uct or ;
poor I nst r uct or = new BankAccount ( ) ;
r i chSt udent . deposi t ( 10000F) ;
poor I nst r uct or . deposi t ( 5. 10F ) ;
Syst em. out . pr i nt l n( " St udent Bal ance: " +
r i chSt udent . bal ance ) ;
Syst em. out . pr i nt l n( " Pr of : " + poor I nst r uct or . t oSt r i ng( ) ) ;
}
}
Output
St udent Bal ance: 10000
Pr of : Account Bal ance: 5. 1



About The Previous Example

"balance" is a field of the class BankAccount
deposit() and toString() are methods of class BankAccount
A method of a class can access the fields of a class
"richStudent" and "poorInstructor" are references to objects
new BankAccount() creates a new object from the class BankAccount and
returns a reference to the object

6/11
When a method change the value of a field, the change remains in effect after
the method ends
The toString() Standard

When required J ava sends toString() message to objects to convert them to
strings
This happens in println() and when adding to strings

In println( richStudent ) the toString() method is used to convert richStudent to a
string

publ i c cl ass RunBank
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
BankAccount r i chSt udent = new BankAccount ( ) ;
BankAccount poor I nst r uct or = new BankAccount ( ) ;
r i chSt udent . deposi t ( 10000F) ;
poor I nst r uct or . deposi t ( 5. 10F ) ;
St r i ng pr of Bal ance = " Pr of : " + poor I nst r uct or ;
Syst em. out . pr i nt l n( pr of Bal ance ) ;
Syst em. out . pr i nt l n( " Pr of : " + poor I nst r uct or ) ;
Syst em. out . pr i nt l n( r i chSt udent ) ;
}
}

Output
Pr of : Account Bal ance: 5. 1
Pr of : Account Bal ance: 5. 1
Account Bal ance: 10000


Initializing Fields

There are three ways in J ava to give a field an initial value:
Direct Assignment
Instance Initialization Block
Constructors

Direct Assignment
publ i c cl ass BankAccount
{
7/11
publ i c f l oat bal ance = 0. 0F;
publ i c voi d deposi t ( f l oat amount )
{
bal ance += amount ;
}
publ i c St r i ng t oSt r i ng( )
{
r et ur n " Account Bal ance: " + bal ance;
}
}


Instance Initialization Blocks

Instance initialization blocks are indicated by blocks of code inside the class, but
outside any method.
Whenever an object is created from a class the code in each instance initialization
block is executed. If there is more than one instance initialization block they are
executed in order, from top to bottom of the class.
Use initialization blocks when the initialization cannot be done in a simple
assignment and needs no extra input parameters.
Direct assignment and constructors are used far more often than initialization
blocks.

publ i c cl ass TaxAccount
{
publ i c doubl e bal ance;

{ / / I nst ance I ni t i al i zat i on bl ock
f l oat baseTaxRat e = . 33F;
f l oat companySi ze = 1. 24F;

bal ance = baseTaxRat e * companySi ze -
Mat h. si n( baseTaxRat e ) + . 013f ;
}
publ i c st at i c voi d mai n( St r i ng[ ] ar gs ) / / Test met hod
{
TaxAccount x = new TaxAccount ( ) ;
Syst em. out . pr i nt l n( x. bal ance) ;
}
}
Output
0. 09815697215174707



Initializing Fields - Constructors

8/11
Constructors have the same name as their class
Constructors have no return type
Constructors have zero or more arguments

Constructors are not methods! You can only call a constuctor using "new ClassName"

Constructors are called when objects are created (using "new")



publ i c cl ass BankAccount
{
publ i c f l oat bal ance;
publ i c BankAccount ( f l oat i ni t i al Bal ance ) / / Const r uct or
{
bal ance = i ni t i al Bal ance;
}
publ i c voi d deposi t ( f l oat amount )
{
bal ance += amount ;
}
publ i c St r i ng t oSt r i ng( )
{
r et ur n " Account Bal ance: " + bal ance;
}
}
publ i c cl ass RunBank
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
BankAccount r i chSt udent = new BankAccount ( 10000F ) ;
BankAccount poor I nst r uct or = new BankAccount ( 5. 10F ) ;
Syst em. out . pr i nt l n( " Pr of : " + poor I nst r uct or ) ;
Syst em. out . pr i nt l n( " St udent : " + r i chSt udent ) ;
}
}
Output
Pr of : Account Bal ance: 5. 1


Multiple Constructors

publ i c cl ass Const r uct or Exampl e {
publ i c Const r uct or Exampl e( ) {
Syst em. out . pr i nt l n( " I n const r uct or - no ar gument " ) ;
}; / / t he ; i s l egal but does not hi ng
publ i c Const r uct or Exampl e( i nt si ze) {
Syst em. out . pr i nt l n( " I n const r uct or - one ar gument " ) ;
}
publ i c voi d Const r uct or Exampl e( ) {
Syst em. out . pr i nt l n( " r et ur n t ype means i t i s " ) ;
Syst em. out . pr i nt l n( " not a const r uct or " ) ;
}
}

9/11

Implicit Constructors
If a class has no constructor the compiler generates an implicit constructor with
no arguments for the class.
If a class has any constructor, the compiler will not generate the implicit
constructor.
If you add a constructor to an existing class, you may need to also add a
constructor with no arguments.



Order of Initialization
When you create an object the direct assignment of fields and instance initialization
blocks are done in order from top to bottom of class, then the constructor is executed

publ i c cl ass Or der Exampl e
{
i nt aFi el d = 1;
{
Syst em. out . pr i nt l n( " Fi r st bl ock: " + aFi el d ) ;
aFi el d++;
}
publ i c Or der Exampl e( )
{
Syst em. out . pr i nt l n( " St ar t Const r uct or : " + aFi el d ) ;
aFi el d++;
Syst em. out . pr i nt l n( " End Const r uct or : " + aFi el d ) ;
}

{
Syst em. out . pr i nt l n( " Second bl ock: " + aFi el d ) ;
aFi el d++;
}


publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
Or der Exampl e t est = new Or der Exampl e( ) ;
}
}
Output
Fi r st bl ock: 1
Second bl ock: 2
St ar t Const r uct or : 3
End Const r uct or : 4


Order of Class Elements Layout

Fields must be declared before they are used in an initialization block
10/11
Guidelines suggest placing all field declaration in one location
place all fields at the beginning of the class or
place all fields at the end of the class


publ i c cl ass Or der Exampl e
{
publ i c Or der Exampl e( )
{
a = 8; / / OK
}

{
a = 4; / / Compi l e Er r or
}

i nt a = 1;

publ i c i nt get C( )
{
r et ur n c;
}

i nt c = 3;

{
a = 4;
}
}


Overloading Methods
The signature of a method is its name with number, type and order of its
parameters.
The return type is not part of the signature of a method.
Two methods in the same class can have the same name if their signatures are
different.

publ i c cl ass Over Load
{
publ i c voi d same( ) {
Syst em. out . pr i nt l n( " No ar gument s" ) ;
}
publ i c voi d same( i nt f i r st Ar gument ) {
Syst em. out . pr i nt l n( " One i nt ar gument s" ) ;
}
publ i c voi d same( char f i r st Ar gument ) {
Syst em. out . pr i nt l n( " One char ar gument s" ) ;
}
publ i c i nt same( i nt f i r st Ar gument ) { / / Compi l e Er r or
Syst em. out . pr i nt l n( " One char ar gument s" ) ;

11/11
r et ur n 5;
}
publ i c voi d same( char f i r st Ar gument , i nt secondAr gument ) {
Syst em. out . pr i nt l n( " char + i nt ar gument s" ) ;
}
publ i c voi d same( i nt f i r st Ar gument , char secondAr gument ) {
Syst em. out . pr i nt l n( " i nt + char ar gument s" ) ;
}
}




this

"this" refers to the current object.
.


publ i c cl ass BankAccount
{
publ i c f l oat bal ance;
publ i c BankAccount ( f l oat i ni t i al Bal ance )
{
t hi s. bal ance = i ni t i al Bal ance; / / do not need t hi s
}
publ i c BankAccount ( i nt bal ance )
{
t hi s. bal ance = bal ance; / / we must need t hi s her e
}
publ i c voi d deposi t ( f l oat amount )
{
bal ance += amount ; / / ok her e
}
publ i c St r i ng t oSt r i ng( )
{
r et ur n " Account Bal ance: " + bal ance;
}
}




*************** End of Lecture 2a **************
1/11
United International University


Course: CSI 211
Course Title: Object Oriented Programming
Lecture 2b: Class and Object variables and references

Access Levels for Fields and Methods

public
Members declared public are accessible anywhere the class is accessible

protected
Members declared protected are directly accessible to any subclasses, and directly
accessible by code in the same package

private
Members declared private are accessible only in the class itself

publ i c cl ass AccessLevel s
{
publ i c i nt publ i cObj ect Var i abl e ;
pr ot ect ed f l oat pr ot ect edObj ect Var i abl e = 10;
pr i vat e i nt [ ] pr i vat eObj ect Var i abl e;
i nt packageAcceess = publ i cObj ect Var i abl e;
publ i c AccessLevel s ( i nt st ar t Val ue )
{
Syst em. out . pr i nt l n( " St ar t Const r uct or " ) ;
pr i vat eObj ect Var i abl e = new i nt [ st ar t Val ue ] ;
}
publ i c voi d sampl eMet hod( i nt val ue )
{
Syst em. out . pr i nt l n( " I n met hod" ) ;
pr i vat eObj ect Var i abl e[ 1 ] = val ue;
}
}
publ i c cl ass Test AccessLevel s
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
AccessLevel s t est = new AccessLevel s ( 11 ) ;
t est . publ i cObj ect Var i abl e = 100; / / Ok
t est . pr ot ect edObj ect Var i abl e= 100; / / Ok
t est . pr i vat eObj ect Var i abl e[ 1 ] = 100; / / Compi l e Er r or
t est . packageAcceess = 100; / / Ok
}
}

2/11
Class Names, Packages, Import, CLASSPATH

Each class belongs to a "package".
Packages are used to group related classes.
A package creates a name space. Classes in different packages can have the same
name.

To put a class in a package, place the statement:

package packageName;

at the beginning of the source file containing the class.

Example

package EDU. sdsu. r oger ;
publ i c cl ass Sampl e {
publ i c voi d hel l o( ) {
Syst em. out . pr i nt l n( " Hel l o f or package sdsu. r oger " ) ;
}
}


Package names are separated into components, which are separated by "."
I n t he above exampl e t he component s ar e " EDU" , " sdsu" , and " r oger



Package Example
package EDU. sdsu. r oger ;

publ i c cl ass Sampl e {
publ i c voi d hel l o( ) {
Syst em. out . pr i nt l n( " Hel l o f or package sdsu. r oger " ) ;
}
}

The class must be in a file named "Sample.java"
Place file "Sample.java" in a directory called "roger"
Place directory "roger" in a directory called "sdsu"
Place directory "sdsu" in a directory "EDU"

The directory "EDU" can be placed anywhere, for completeness of the example I place it
in the directory "/home/ma/whitney/java"

Make sur e t hat " / home/ ma/ whi t ney/ j ava" i n t he CLASSPATH envi r onment
var i abl e

3/11


Import Statement

The import statement allows you to use short class names
Both the examples below will compile and run

With Import, Short Name
i mpor t EDU. sdsu. r oger . Sampl e;
publ i c cl ass Test Package {
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) {
Sampl e me = new Sampl e( ) ;
me. hel l o( ) ;
}
}

Without Import, Full Name

publ i c cl ass Test Package {
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) {
EDU. sdsu. r oger . Sampl e me =
new EDU. sdsu. r oger . Sampl e( ) ;
me. hel l o( ) ;
}
}
Object Variables are References
Two objects references, sam and samTwin, referencing the same object. This is
demonstrated by using the samTwin reference to change the value of the field grade, and
using the reference sam to display the new value.
publ i c cl ass St udent
{
publ i c char gr ade;
}

publ i c cl ass Poi nt er Test
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
St udent sam = new St udent ( ) ;
sam. gr ade = ' A' ;
St udent samTwi n = sam;
samTwi n. gr ade = ' C' ;
Syst em. out . pr i nt l n( sam. gr ade ) ;
}
}
Output
C


4/11
Parameter Passing & Objects

publ i c cl ass St udent
{
publ i c char gr ade;
}
publ i c cl ass Test Par amet er
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
St udent sam = new St udent ( ) ;
sam. gr ade = ' C' ;
changeRef er ence( sam ) ;
Syst em. out . pr i nt l n( sam. gr ade ) ;
changeSt at e( sam ) ;
Syst em. out . pr i nt l n( sam. gr ade ) ;
}
publ i c st at i c voi d changeSt at e( St udent l ucky )
{
l ucky. gr ade = ' A' ;
}
publ i c st at i c voi d changeRef er ence( St udent unl ucky )
{
unl ucky = new St udent ( ) ; / / Par amet er Passi ng - By val ue onl y
unl ucky. gr ade = ' A' ;
}
}
Output
C
A
Static Qualifier
Static Fields
There is only one copy of a static field
All objects created from the class reference the same copy of a static field
A static field exists before creating an object of the class

publ i c cl ass St at i cFi el ds
{
publ i c st at i c i nt si ze = 10;
publ i c voi d i ncr easeSi ze( i nt i ncr ement )
{
si ze = si ze + i ncr ement ;
}
}
publ i c cl ass DemoSt at i cFi el ds
{
5/11
publ i c st at i c voi d mai n( St r i ng[ ] ar gument s )
{
Syst em. out . pr i nt l n( " Si ze " + St at i cFi el ds. si ze ) ;
St at i cFi el ds t op = new St at i cFi el ds( ) ;
St at i cFi el ds bot t om = new St at i cFi el ds( ) ;
t op. si ze = 20;
Syst em. out . pr i nt l n( " Si ze " + bot t om. si ze ) ;
}
}
Output
Si ze 10
Si ze 20

Static Methods (Class Methods)
Static methods can only access static fields and other static methods in the class
Static methods can be referenced via an object or the class
publ i c cl ass St at i cMet hods
{
publ i c st at i c i nt si ze = 10;
publ i c st at i c voi d i ncr easeSi ze( i nt i ncr ement )
{
si ze = si ze + i ncr ement ;
}
}
publ i c cl ass DemoSt at i cMet hods
{
publ i c st at i c voi d mai n( St r i ng[ ] ar gument s )
{
St at i cMet hods. i ncr easeSi ze( 30 ) ; / / Not e use of cl ass name
Syst em. out . pr i nt l n( " Si ze " + St at i cMet hods. si ze ) ;
St at i cMet hods t op = new St at i cMet hods( ) ;
t op. i ncr easeSi ze( 20 ) ;
Syst em. out . pr i nt l n( " Si ze " + St at i cMet hods. si ze ) ;
}
}
Output
Si ze 40
Si ze 60
Static Initialization Blocks
A static initialization block is an initialization block preceded with the quantifier
"static".
A static initialization block is normally executed only once each time your
program is run.

UIU Lecture 2b, CSI 211
6/11
It will be executed before any object is created or any reference is to the class is
actually made in your program.
If more than one static block exists in the class, then they are executed in order,
from top to bottom of the class.
The static block can only reference static methods and static fields. Any static
field referenced in the static block must be declared before the static block. This
restriction does not hold for static methods.




publ i c cl ass St at i cFi el ds {
publ i c st at i c i nt si ze = 10;
st at i c { / / Run when cl ass i s f i r st l oaded
si ze = cl assMet hod( 20) ;
Syst em. out . pr i nt l n( si ze ) ;
}
publ i c st at i c i nt cl assMet hod( i nt val ue ) {
Syst em. out . pr i nt l n( " I n cl ass met hod" ) ;
r et ur n val ue + 10;
}
}
publ i c cl ass Test St at i cFi el ds {
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) {
Syst em. out . pr i nt l n( " St ar t Test " ) ;
St at i cFi el ds t est = new St at i cFi el ds ( ) ;
St at i cFi el ds secondObj ect = new St at i cFi el ds ( ) ;
St at i cFi el ds. si ze = 100;
Syst em. out . pr i nt l n( t est . si ze ) ; / / Pr i nt 100
}
}
Output
St ar t Test
I n cl ass met hod
30
100

Main method
There is nothing magic about the method "public static void main( String[] args
)." When you execute a class with the command "java className" The J VM
looks for a method called main with the exact signature and return type i.e.
"public static void main( String[] args ).
If the main does not have the proper signature and return time, the J VM will
report an error. So the main in OddMain below can not be used to start the class.

UIU Lecture 2b, CSI 211
7/11
However, the method "main" can be called from your code like any other static
method, as is done in the next example. This does mean that your program can
have multiple entry points, as the next example shows.
publ i c cl ass Top {
publ i c st at i c voi d mai n( St r i ng[ ] ar gument s ) {
Syst em. out . pr i nt l n( " I n t op mai n" ) ;
Bot t om. mai n( ar gument s ) ;
}
publ i c st at i c voi d pr i nt ( ) {
Syst em. out . pr i nt l n( " I n t op" ) ;
}
}
publ i c cl ass Bot t om{
publ i c st at i c voi d mai n( St r i ng[ ] ar gument s ) {
Syst em. out . pr i nt l n( " I n bot t ommai n" ) ;
Top. pr i nt ( ) ;
OddMai n. mai n( ar gument s ) ;
}
}
publ i c cl ass OddMai n {
publ i c st at i c i nt mai n( St r i ng[ ] ar gument s ) {
/ / si gnat ur e di f f er ent
Syst em. out . pr i nt l n( " I n odd mai n" ) ;
Top hat = new Top( ) ;
hat . pr i nt ( ) ;
r et ur n 5;
}
}
Constant Fields

Declaring a field final means that it can only be set once
publ i c cl ass Const ant s
{
pr ot ect ed f i nal i nt SI ZE = 10;
pr ot ect ed f i nal i nt [ ] CLASS_ARRAY = new i nt [ SI ZE ] ;
pr ot ect ed f i nal i nt NO_VALUE_YET; / / bl ank f i nal
publ i c voi d aMet hod( i nt i nput , f i nal f l oat FI XED)
{
f i nal i nt NEW_FEATURE = 123;
f i nal i nt ALSO_FI XED = i nput ;
CLASS_ARRAY[ 3 ] = i nput ;
}

publ i c Const ant s( i nt aVal ue )
{
NO_VALUE_YET = aVal ue;
}

publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{

UIU Lecture 2b, CSI 211
8/11
Const ant s t est = new Const ant s( 5) ;
t est . aMet hod( 13, 2. 2f ) ;
Syst em. out . pr i nt l n( t est . NO_VALUE_YET ) ; / / Pr i nt s 5
}
}

Blank Final Rules
A blank final is a final variable declaration that lacks an initializer
A blank final must be assigned exactly once
A blank final class (static) variable must be assigned by one static initialization
block
blank final class variable can not be assigned in more than one static
initialization block
A blank final instance variable can not be assigned in a non-static initialization
block and a constructor
publ i c cl ass St at i cConst ant s
{
pr ot ect ed st at i c f i nal i nt SI ZE;
st at i c
{
SI ZE = 123;
}
}
publ i c cl ass Const ant s
{
pr ot ect ed f i nal i nt SI ZE;
{
SI ZE = 123; / / compi l er er r or
}
}

Polymorphism


Polymorphism. Poly means many and morph means form. Thus,
polymorphism refers to being able to use many forms of a type without regard
to the details.


UIU Lecture 2b, CSI 211
9/11
Example using Interface


import j ava. ut i l . Random;

class Shape {
void dr aw( ) {
}

void er ase( ) {
}
}

class Ci r cl e extends Shape {
void dr aw( ) {
Syst em. out . pr i nt l n( " Ci r cl e. dr aw( ) " ) ;
}

void er ase( ) {
Syst em. out . pr i nt l n( " Ci r cl e. er ase( ) " ) ;
}
}

class Squar e extends Shape {
void dr aw( ) {
Syst em. out . pr i nt l n( " Squar e. dr aw( ) " ) ;
}

void er ase( ) {
Syst em. out . pr i nt l n( " Squar e. er ase( ) " ) ;
}
}

class Tr i angl e extends Shape {
void dr aw( ) {
Syst em. out . pr i nt l n( " Tr i angl e. dr aw( ) " ) ;
}

void er ase( ) {
Syst em. out . pr i nt l n( " Tr i angl e. er ase( ) " ) ;
}
}

/ / A " f act or y" t hat r andoml y cr eat es shapes:

class RandomShapeGener at or {
private Randomr and = new Random( ) ;

public Shape next ( ) {
switch ( r and. next I nt ( 3) ) {
default:
case 0:
return new Ci r cl e( ) ;
case 1:
return new Squar e( ) ;
case 2:

UIU Lecture 2b, CSI 211
10/11
return new Tr i angl e( ) ;
}
}
}

public class ShapesDemo {
private static RandomShapeGener at or gen = new RandomShapeGener at or ( ) ;

public static void mai n( St r i ng[ ] ar gs) {
Shape[ ] s = new Shape[ 9] ;
/ / Fi l l up t he ar r ay wi t h shapes:
for ( int i = 0; i < s. l engt h; i ++)
s[ i ] = gen. next ( ) ;
/ / Make pol ymor phi c met hod cal l s:
for ( int i = 0; i < s. l engt h; i ++)
s[ i ] . dr aw( ) ;

}
} / / / : ~


Example using Abstract classes

publ i c abst r act cl ass Ani mal / / cl ass i s abst r act
{
pr i vat e St r i ng name;
publ i c Ani mal ( St r i ng nm) / / const r uct or met hod
{
name=nm;
}
publ i c St r i ng get Name( ) / / r egul ar met hod
{
r et ur n ( name) ;
}
publ i c abst r act voi d speak( ) ; / / abst r act met hod - not e no {}
}

publ i c cl ass Dog ext ends Ani mal
{
publ i c Dog( St r i ng nm)
{
super ( nm) ; / / bui l ds par ent
}
publ i c voi d speak( ) / / t hi s met hod speci f i c t o ani mal
{
Syst em. out . pr i nt l n( " Dog speaks" ) ;
}
}

UIU Lecture 2b, CSI 211
11/11
publ i c cl ass Cat ext ends Ani mal
{
publ i c Dog( St r i ng nm)
{
super ( nm) ; / / bui l ds par ent
}
publ i c voi d speak( ) / / t hi s met hod speci f i c t o ani mal
{
Syst em. out . pr i nt l n( " Cat speaks" ) ;
}
}

publ i c cl ass Ani mal Ref er ence
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
Ani mal r ef / / set up var f or an Ani mal
Cat aCat = new Cat ( " Bossy" ) ; / / makes speci f i c obj ect s
Dog aDog = new Dog( " Rover " ) ;

/ / now r ef er ence each as an Ani mal
r ef = aCat ; r ef . speak( ) ;
r ef = aDog; r ef . speak( ) ;
}


*************** End of Lecture 2b **************

UIU Lecture 3a, CSI 211
1/8
United International University

Course: CSI 211
Course Title: Object Oriented Programming
Lecture 3a: Object oriented concept, Information hiding; examples.

Objects and Constant Variables
When an object reference is final, as is "object" below, the reference can be
assigned only once. The state of the object can change. This is shown below
where the state of "object" is legally changed by directly accessing the field and
using a method. However, assigning a new reference to the variable "object" is
not allowed.
publ i c cl ass Test
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
f i nal Sampl e obj ect = new Sampl e( ) ;
obj ect . dat a = 5; / / OK
obj ect . set Dat a( 12 ) ; / / OK
obj ect = new Sampl e( ) ; / / Compi l e Er r or
}
}
publ i c cl ass Sampl e
{
publ i c i nt dat a = 3;

publ i c voi d set Dat a( i nt newVal ue )
{
dat a = newVal ue;
}
}

Initialization Order
A class is initialized when it is first "actively" used, i.e.
o A method defined in the class is invoked
o A constructor in the class is invoked
o A non-constant field in the class is accessed
A class is initialized by performing direct assignments of static fields and static
initialization blocks are done in order from top to bottom of the class

UIU Lecture 3a, CSI 211
2/8
When an object is created, after the class in initialized, all instance field are
initialized by:
o performing direct assignments of non-static fields and instance
initialization blocks are done in order from top to bottom of the class,
then the constructor is executed
When you initialize a field you can not make a forward reference another field
publ i c cl ass For war dRef er enceAndI ni t i al i zat i on
{
publ i c st at i c i nt f i r st = 1;
publ i c st at i c i nt second = f i r st * 2;
publ i c st at i c i nt t hi r d = f our t h - 1; / / Compi l er er r or
publ i c st at i c i nt f our t h = 4;
publ i c i nt f i f t h = 5;
publ i c i nt si xt h = f i f t h + 1;
publ i c i nt sevent h = ei ght h - 1; / / Compi l er er r or
publ i c i nt ei ght h = 8;
}


When initializing a field you can make a forward reference to a method
publ i c cl ass For war dRef er enceAndFunct i ons
{
publ i c i nt f i f t h = get Si xt h( ) ;
publ i c i nt si xt h = f i f t h + 1;
publ i c i nt sevent h = get Si xt h( ) ;
publ i c i nt get Si xt h( )
{
r et ur n si xt h;
}
}





publ i c cl ass Test
{
publ i c st at i c voi d mai n( St r i ng[ ] ar gument s )
{
For war dRef er enceAndFunct i ons wor ks;
wor ks = new For war dRef er enceAndFunct i ons( ) ;
Syst em. out . pr i nt l n( " f i f t h " + wor ks. f i f t h ) ;
Syst em. out . pr i nt l n( " si xt h " + wor ks. si xt h ) ;
Syst em. out . pr i nt l n( " sevent h " + wor ks. sevent h ) ;
}
}
Output
f i f t h 0
si xt h 1

UIU Lecture 3a, CSI 211
3/8
sevent h 1
Recursion
It is the process of a method calling itself. A recursion has two parts
stop condition
call itself
Recursion is an expensive procedure and it is better to avoid recursion if you do not need
package l ect ur e02b;


public class MyMat hLi br ar y {

public static int f act or i al ( int n) {
if ( n <= 0)
return 1; / / st op condi t i on
return n * factorial( n- 1) ; / / cal l i t sel f
}
public static void mai n( St r i ng[ ] ar gs ) {

Syst em. out. pr i nt ( " Fact or i al of 5 i s: " + factorial( 5) ) ;

}
}


UIU Lecture 3a, CSI 211
4/8
Class Example - Stack
"A stack is a linear list for which all insertions and deletions are made at one end of the
list"
Operations pop, push, isEmpty, isFull
The following Stack class is not a production level class.

cl ass St ack {
pr i vat e f l oat [ ] el ement s;
pr i vat e i nt t opOf St ack = - 1;

publ i c St ack( i nt st ackSi ze ) {
el ement s = new f l oat [ st ackSi ze ] ;
}

publ i c voi d push( f l oat i t em) {
el ement s[ ++t opOf St ack ] = i t em;
}

publ i c f l oat pop( ) {
r et ur n el ement s[ t opOf St ack- - ] ;
}

publ i c bool ean i sEmpt y( ) {
i f ( t opOf St ack < 0 ) r et ur n t r ue;
el se r et ur n f al se;
}

publ i c bool ean i sFul l ( ) {
i f ( t opOf St ack >= el ement s. l engt h ) r et ur n t r ue;
el se r et ur n f al se;
}
}

UIU Lecture 3a, CSI 211
5/8
Using the Stack
..
St ack me = new St ack( 20 ) ;
me. push( 5 ) ;
me. push( 12 ) ;
Syst em. out . pr i nt l n( me. pop( ) ) ;
Syst em. out . pr i nt l n( me. pop( ) ) ;
. .


A Struct Version - C Programming

st r uct St ack
{
f l oat st ack[ 100] ;
i nt t opOf St ack;
};
voi d push( St ack& i t , i nt i t em)
{
i t . st ack[ ( i t . t opOf St ack) ++] = i t em;
}
f l oat pop( St ack& i t )
{
r et ur n i t . st ack[ - - ( i t . t opOf St ack) ] ;
}
mai n( )
{
St ack t r yThi sOut ;
St ack your s, mi ne;
t r yThi sOut . t opOf St ack = 0; / / i nf or mat i on i s not hi dden!
your s. t opOf St ack = 0;
push( t r yThi sOut , 5. 0 ) ;
push( your s, 3. 3 ) ;
push( t r yThi sOut , 9. 9 ) ;
cout << pop( t r yThi sOut ) << endl ;
}

Problems with the Struct Version - Encapsulation

Data is encapsulated
Operations are not encapsulated with data
The boundaries of what it is become fuzzy


Information hiding

Data is not hidden Data is not safe! In the above example of Stack class you will not be
allowed to do the following.

St ack t r oubl eAhead;
t r oubl eAhead. t opOf St ack = 13; / / compi l e er r or !
t r oubl eAhead. st ack[ 8 ] = 29;

UIU Lecture 3a, CSI 211
6/8
Some Typical Beginners
Mistake #1
Struct-like Class

One can make a class that is just a struct dressed as a class. Avoid this doing this.
cl ass St ackDat a
{
publ i c f l oat [ ] el ement s = new f l oat [ 100] ;
publ i c i nt t opOf St ack = 0;
}

cl ass Test
{
st at i c voi d push( St ack i t , i nt i t em)
{
i t . st ack[ ( i t . t opOf St ack ) ++ ] = i t em;
}
st at i c f l oat pop( St ack i t )
{
r et ur n i t . st ack[ - - ( i t . t opOf St ack) ] ;
}
publ i c voi d st at i c mai n( St r i ng[ ] ar gs)
{
St ack your s, mi ne;
push( your s, 3. 3 ) ;
push( mi ne, 9. 9) ;
}

}
Mistake #2
This example has all fields hidden. But the methods do not support the stack abstraction.
The logic of operating the stack is not in the stack class. This means that the topOfStack
field can be improperly set by some one outside the class.
cl ass St ackDat a
{
pr i vat e f l oat [ ] el ement s = new f l oat [ 100] ;
pr i vat e i nt t opOf St ack = - 1;
publ i c i nt get TopOf St ack( )
{
r et ur n t opOf St ack;
}
publ i c voi d set TopOf St ack( i nt newTop )
{
t opOf St ack = newTop;
}



UIU Lecture 3a, CSI 211
7/8
publ i c f l oat get El ement ( i nt el ement I ndex )
{
r et ur n el ement s[ el ement I ndex ] ;
}
publ i c voi d set El ement ( i nt el ement I ndex, f l oat el ement )
{
el ement s[ el ement I ndex ] = el ement ;
}
}

Mistake #3
Adding IO to the push and pop methods make the stack class unusable. This often
happens in new student programs.
cl ass St ack {
pr i vat e f l oat [ ] el ement s = new f l oat [ 100 ] ;
pr i vat e i nt t opOf St ack = - 1;

publ i c voi d push( )
{
f l oat i t em= Consol e. r eadFl oat ( " Type a f l oat t o push" ) ;
el ement s[ ++t opOf St ack ] = i t em;
}

publ i c voi d pop( )
{
Consol e. pr i nt l n( " Top st ack i t em: " +
el ement s[ t opOf St ack- - ] ;
}
}

cl ass Test
{
publ i c voi d st at i c mai n( St r i ng[ ] ar gs)
{
St ack your s ohNo = new St ack( ) ;
ohNo. push( ) ;
ohNo. push( ) ;
ohNo. pop( ) ;
}





UIU Lecture 3a, CSI 211
8/8
Design Heuristics
All data should be hidden within its class
A class should capture one and only one key abstraction - do not mix many
classes in one class.
Keep related data and behavior in one place
Beware of classes that have many accessor methods in their public interface.
This implies data and behavior are not in one place
Applying these heuristics to your classes will go a long way to help you avoid typical
beginner mistakes in designing classes





*************** End of Lecture 3a **************

UIU Lecture 3b, CSI 211
1/11
United International University

Course: CSI 211
Course Title: Object Oriented Programming
Lecture 3b: Inheritance and Class relationships.


Inheritance
inheritance is a way to form new classes (instances of which are called objects)
using classes that have already been defined.
The new classes, known as derived classes, take over (or inherit) attributes and
behavior of the pre-existing classes, which are referred to as base classes (or
ancestor classes).
It is intended to help reuse existing code with little or no modification.

cl ass Par ent {
publ i c i nt par ent Var i abl e = 10;
publ i c voi d par ent Funct i on( ) {
Syst em. out . pr i nt l n( " Par ent Funct i on" ) ;
}
}
cl ass Chi l d ext ends Par ent {
publ i c voi d chi l dFunct i on( ) {
par ent Funct i on( ) ;
Syst em. out . pr i nt l n( " I n Chi l d " + par ent Var i abl e ) ;
}
}
cl ass I nher i t ance {
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) {

Chi l d exampl e = new Chi l d( ) ;
exampl e. chi l dFunct i on( ) ;
exampl e. par ent Funct i on( ) ;
Syst em. out . pr i nt l n( exampl e. par ent Var i abl e ) ;
}
}

Output
Par ent Funct i on
I n Chi l d 10
Par ent Funct i on
10



Inheritance

UIU Lecture 3b, CSI 211
2/11

A class can be extended or subclassed
The class that is extended is a superclass
Some people use the words parent class or base class to mean a superclass
The extended class is a subclass or extended class of its superclass
Some people use the word child class to mean subclass
An object created from the subclass has its own copy of all the nonstatic fields
defined in its superclass
J ava does not support multiple inheritance

Class Object

All classes inherit directly or indirectly from java.lang.Object
- class Parent { int size; }
- class Parent extends Object { int size; }

The child class below is a grandchild of Object

- Having a common ancestor class allows java to provide standards on all objects, like
toString()
cl ass Par ent { i nt si ze; }
cl ass Chi l d ext ends Par ent { i nt age; }
cl ass Test Obj ect {
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) {
Par ent wat chThi s = new Par ent ( ) ;
i nt myHash = wat chThi s. hashCode( ) ;
Syst em. out . pr i nt l n( myHash ) ;
/ / Wher e does hashCode come f r om?
}
}



UIU Lecture 3b, CSI 211
3/11
Some Object's Methods

clone() - Creates a clone of the object.

equals(Object) - Compares two Objects for equality.
Uses "==" to test for equality

toString() - Returns a String that represents the value of this Object.

If a class needs an implementation of equals, which differs from the default
"equals", the class should override both equals and hashCode
If two different objects satisfy the equals method, the hashCode should return the
same value for both objects

Casting and Classes
An instance of a child class can be assigned to a variable (field) of the parent
class.
If a variable references an object of a subclass, the object can be cast down to its
actual type with an explicit cast. The explicit cast is required. A runtime error
occurs when explicitly casting an object to a type that it is not.
In the code below the cast "(Uncle) object" is a runtime error because at that time
object holds an instance of the Child class, which is not of type (or subclass) of
Uncle. An object of type Parent cannot be cast to type Child.


cl ass Par ent { i nt dat a; }
cl ass Chi l d ext ends Par ent { St r i ng name; }
cl ass Uncl e { St r i ng r i ch; }
cl ass Cast i ng {
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) {
Obj ect obj ect ;
Par ent par ent ;
Chi l d chi l d = new Chi l d( ) ;

UIU Lecture 3b, CSI 211
4/11
Uncl e uncl e;
par ent = chi l d;
obj ect = chi l d;
par ent = ( Par ent ) obj ect ; / / expl i ci t cast down
chi l d = ( Chi l d) obj ect ; / / expl i ci t cast down
uncl e = ( Uncl e) obj ect ; / / Runt i me except i on
}
}

Output
j ava. l ang. Cl assCast Except i on: Chi l d: cannot cast t o Uncl e



Inheritance and Name Clashes

What happens when the parent class has a method(field) with the same name as a
method(field) of the child class?
Terms and Rules
Overloading
Providing more than one method with the same name, but with different signatures
Overriding
A class replacing an ancestor's implementation of a method with an implementation of it
own Signature and return type must be the same .
Static methods can not be overridden



Overriding Methods
Note that the statement "overRidden.print();" prints out different text depending on what
type of object overRidden references.
cl ass Par ent {
publ i c voi d pr i nt ( ) {
Syst em. out . pr i nt l n( " I n Par ent " ) ;
}
}
cl ass Chi l d ext ends Par ent {
publ i c voi d pr i nt ( ) {
Syst em. out . pr i nt l n( " I n Chi l d" ) ;
}
}
cl ass Over r i ddi ngMet hods {

UIU Lecture 3b, CSI 211
5/11
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) {
Chi l d whoAmI = new Chi l d( ) ;
whoAmI . pr i nt ( ) ;
Par ent over Ri dden = whoAmI ;
over Ri dden. pr i nt ( ) ;
over Ri dden = new Par ent ( ) ;
over Ri dden. pr i nt ( ) ;
}
}

Output
I n Chi l d
I n Chi l d
I n Par ent



Overriding and Return Types
When overriding a method, the child's method must have the same signature and
return type as the parent's method.

cl ass Par ent {
publ i c voi d pr i nt ( ) {
Syst em. out . pr i nt l n( " I n Par ent " ) ;
}

publ i c voi d pr i nt ( St r i ng message ) {
Syst em. out . pr i nt l n( " I n Par ent " + ' \ t ' + message ) ;
}
publ i c voi d pr i nt ( i nt val ue ) {
Syst em. out . pr i nt l n( " I n Par ent " + ' \ t ' + val ue ) ;
}
}
cl ass Chi l d ext ends Par ent {
publ i c i nt pr i nt ( ) { / / Compi l er Er r or
Syst em. out . pr i nt l n( " I n Chi l d" ) ;
r et ur n 5;
}
publ i c voi d pr i nt ( St r i ng message ) {
Syst em. out . pr i nt l n( " I n Chi l d" + ' \ t ' + message ) ;
}
}
cl ass Ret ur nTypesCount {
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) {
Chi l d whoAmI = new Chi l d( ) ;
whoAmI . pr i nt ( ) ;
whoAmI . pr i nt ( " Hi Mom" ) ;
whoAmI . pr i nt ( 10 ) ; / / Ok i n J ava,
/ / Compi l e er r or i n C++
}
}




UIU Lecture 3b, CSI 211
6/11
Super
Refers to the superclass of class that implements the method containing the
reference to super
All references to super are resolved statically

To find out what class super refers to go to the source code, find the code that contains
"super", then go to that classes parent class.
cl ass Par ent { St r i ng name = " Par ent " ; }
cl ass Chi l d ext ends Par ent {
St r i ng name = " Chi l d" ;
publ i c voi d pr i nt ( ) {
Syst em. out . pr i nt l n( name ) ;
Syst em. out . pr i nt l n( super . name ) ;
}
}
cl ass Gr andChi l d ext end Chi l d {
St r i ng name = " Gr andChi l d" ;
}
cl ass Super Mai n {
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) {
Gr andChi l d whoAmI = new Gr andChi l d( ) ;
whoAmI . pr i nt ( ) ;
}
}
Output
Chi l d
Par ent


super.super

- J ava does not al l ow you t o chai n super s t o r ef er t o your gr andpar ent
cl ass

- super . super i s not al l owed i n J ava


Constructors and Inheritance
Before the constructor in a Child class is called, its parent's constructor will be called

a) Implicit Call to Parent's Constructor

cl ass Par ent {
publ i c Par ent ( ) {
Syst em. out . pr i nt l n( " \ t I n Par ent " ) ;
}
}

UIU Lecture 3b, CSI 211
7/11
cl ass Chi l d ext ends Par ent {
publ i c Chi l d( ) {
Syst em. out . pr i nt l n( " \ t I n Chi l d" ) ;
}
publ i c Chi l d( St r i ng not Used ) {
Syst em. out . pr i nt l n( " \ t I n Chi l d wi t h ar gument " ) ;
}
}
cl ass Const r uct or s {
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) {
Syst em. out . pr i nt l n( " Const r uct Par ent " ) ;
Par ent sl eepy = new Par ent ( ) ;
Syst em. out . pr i nt l n( " Const r uct Chi l d" ) ;
Chi l d car e = new Chi l d( ) ;
Syst em. out . pr i nt l n( " Const r uct Second Chi l d" ) ;
car e = new Chi l d( " Tr y Me" ) ;
}
}

Output
Const r uct Par ent
I n Par ent
Const r uct Chi l d
I n Par ent
I n Chi l d
Const r uct Second Chi l d
I n Par ent
I n Chi l d wi t h ar gument




b) Explicit Call to Parent's Constructors

cl ass Par ent {
publ i c Par ent ( ) {
Syst em. out . pr i nt l n( " I n Par ent , No Ar gument " ) ;
}
publ i c Par ent ( St r i ng message ) {
Syst em. out . pr i nt l n( " I n Par ent " + message ) ;
}
}
cl ass Chi l d ext ends Par ent {
publ i c Chi l d( St r i ng message, i nt val ue ) {
t hi s( message ) ; / / i f occur s must be
f i r st
Syst em. out . pr i nt l n( " I n Chi l d" ) ;
}
publ i c Chi l d( St r i ng message ) {
super ( message ) ; / / i f occur s must be f i r st
Syst em. out . pr i nt l n( " I n Chi l d" + message ) ;
}
}
cl ass Const r uct or s {
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) {
Syst em. out . pr i nt l n( " Const r uct Chi l d" ) ;

UIU Lecture 3b, CSI 211
8/11
Chi l d car e = new Chi l d( " >St ar t f r omChi l d<" , 5 ) ;
}
}

Output
Const r uct Chi l d
I n Par ent >St ar t f r omChi l d<
I n Chi l d>St ar t f r omChi l d<
I n Chi l d


No Default Parent Constructor

The compiler will not generate the default constructor for the class "Parent", since
"Parent" has a constructor. The class "Child" makes an implicit call to the default
constructor in "Parent". This causes a compile error.
cl ass Par ent {
publ i c Par ent ( St r i ng message ) {
Syst em. out . pr i nt l n( " I n Par ent " + message ) ;
}
}
cl ass Chi l d ext ends Par ent {
publ i c Chi l d( ) { / / Compi l e Er r or
Syst em. out . pr i nt l n( " I n Chi l d" ) ;
}
publ i c Chi l d( St r i ng message ) {
super ( message ) ;
Syst em. out . pr i nt l n( " I n Chi l d" + message ) ;
}
}
Access Levels and Inheritance
Private Access
Private class members are accessible only in the class they are defined
cl ass Pr i vat e {
pr i vat e St r i ng name = " Pr i vat e" ;
publ i c voi d pr i nt ( ) {
Syst em. out . pr i nt l n( name ) ;
}
publ i c voi d t r i cky( Pr i vat e ar gument ) {
ar gument . name = " Thi s access i s l egal " ;
}
}
cl ass Excl uded ext ends Pr i vat e {
publ i c voi d cant Pr i nt ( ) {
Syst em. out . pr i nt l n( name ) ; / / Compi l e er r or
}
}
cl ass Pr i vat eExampl e {

UIU Lecture 3b, CSI 211
9/11
publ i c st at i c voi d mai n( St r i ng[ ] ar gs ) {
Pr i vat e t op = new Pr i vat e( ) ;
Pr i vat e bot t om= new Pr i vat e( ) ;
t op. t r i cky( bot t om) ;
bot t om. pr i nt ( ) ;
}
}

Output (if compile error is removed )
Thi s access i s l egal


Since a private method can not be called from the child, when an inherited
method (foo) calls the parent private method (Parent.bar), the parent private
method is always the one called
cl ass A {
publ i c voi d f oo( ) {
bar ( ) ;
}
pr i vat e voi d bar ( ) {
Syst em. out . pr i nt l n( " A" ) ;
}
}
cl ass B ext ends A {
publ i c voi d bar ( ) {
Syst em. out . pr i nt l n( " B" ) ;
}
publ i c st at i c voi d mai n( St r i ng[ ] ar gs ) {
A a = new A ( ) ;
a. f oo( ) ;
}
}
Output
A


Protected Access
protected Accessible in the package that contains the class
Accessible in all subclasses

package Bot any;
publ i c cl ass Pr ot ect ed {
pr ot ect ed St r i ng name = " Pr ot ect ed" ;
}
package Bot any;
publ i c cl ass NoRel at i on {
publ i c voi d Sampl eAccess( Pr ot ect ed accessOK ) {
accessOK. name = " Thi s i s l egal " ;
}
}
package Tr ee;
publ i c cl ass NoRel at i onEi t her {

UIU Lecture 3b, CSI 211
10/11
publ i c voi d Sampl eAccess( Bot any. Pr ot ect ed noAccess) {
noAccess. name = " Thi s i s a compi l e Er r or " ;
}
}
package Tr ee;
publ i c cl ass Chi l d ext ends Bot any. Pr ot ect ed {
publ i c voi d Sampl eAccess( Bot any. Pr ot ect ed noAccess,
Chi l d accessOK) {
name = " Thi s i s l egal , I amr el at ed" ;
noAccess. name = " Thi s i s a compi l e Er r or " ;
accessOK. name = " Thi s i s l egal " ;
}
}




Package Access

Accessible in the package that contains the class
Not accessible outside the package that contains the class

package Bot any;
publ i c cl ass NoExpl i ci t {
St r i ng name = " No expl i ci t access l evel gi ven" ;
}
package Bot any;
publ i c cl ass NoRel at i on {
publ i c voi d Sampl eAccess( NoExpl i ci t accessOK ) {
accessOK. name = " Thi s i s l egal " ;
}
}
package Tr ee;
publ i c cl ass NoRel at i onEi t her {
publ i c voi d Sampl eAccess( Bot any. NoExpl i ci t noAccess) {
noAccess. name = " Thi s i s a compi l e Er r or " ;
}
}
package Tr ee;
publ i c cl ass Chi l d ext ends Bot any. NoExpl i ci t {
publ i c voi d Sampl eAccess( Bot any. NoExpl i ci t noAccess,
Chi l d al soNoAccess) {
name = " I amr el at ed, but t hi s i s NOT LEGAL" ;
noAccess. name = " Thi s i s a compi l e Er r or " ;
al soNoAccess. name = " Thi s i s a compi l e Er r or " ;
}
}

Public Access
Accessible by any one

}



UIU Lecture 3b, CSI 211
11/11





*************** End of Lecture 3a **************

UIU Lecture 4a, CSI 211
1/12
United International University

Course: CSI 211
Course Title: Object Oriented Programming
Lecture 3a: Interfaces.

Final

The final modifier provides:
Security
Performance optimizations
A class declared final, can not have any subclasses

f i nal cl ass EndOf TheLi ne {
i nt noSubcl assPossi bl e;
publ i c voi d aFunct i on( ) {
Syst em. out . pr i nt l n( " Hi Mom" ) ;
}
}

cl ass Thi sWi l l Not Wor k ext ends EndOf TheLi ne {
i nt ohNo;
}
Does not compile


Final Method
A final method can not be overridden
cl ass Par ent {
publ i c f i nal voi d t heEnd( ) {
Syst em. out . pr i nt l n( " Thi s i s i t " ) ;
}
publ i c voi d nor mal ( ) {
Syst em. out . pr i nt l n( " I n par ent " ) ;
}
}
cl ass Chi l d ext ends Par ent {
publ i c voi d t heEnd( ) { / / Compi l e Er r or
Syst em. out . pr i nt l n( " Two Ends?" ) ;
}
publ i c voi d nor mal ( ) {
Syst em. out . pr i nt l n( " I n Chi l d" ) ;
}
}

Abstract class and abstract Method

UIU Lecture 4a, CSI 211
2/12

An abstract class is a class that is declared abst r act it may or may not include
abstract methods.
o Abstract classes cannot be instantiated, but they can be subclassed.
o When an abstract class is subclassed, the subclass usually provides
implementations for all of the abstract methods in its parent class.
o if it does not, the subclass must also be declared abst r act
An abstract method is a method that is declared without an implementation
(without braces, and followed by a semicolon), like this:
abst r act cl ass NoObj ect s {
i nt noDi r ect Obj ect Possi bl e = 5;
publ i c voi d aFunct i on( ) {
Syst em. out . pr i nt l n( " Hi Mom" ) ;
}
publ i c abst r act voi d subCl assMust I mpl ement ( i nt f oo ) ;
}
cl ass Concr et e ext ends NoObj ect s {
publ i c voi d subCl assMust I mpl ement ( i nt f oo ) {
Syst em. out . pr i nt l n( " I n Concr et e" ) ;
}
}
cl ass Abst r act Cl asses {
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) {
NoObj ect s usef ul = new Concr et e( ) ;
Concr et e t hi sWor ks = new Concr et e( ) ;
usef ul . subCl assMust I mpl ement ( 10 ) ;

Syst em. out . pr i nt l n( t hi sWor ks. noDi r ect Obj ect Possi bl e ) ;
}
}
Output
I n Concr et e



Relationships between Classes
Is-kind-of / is-a / is-a-type-of
is-analogous-to
is-part-of or has-a




a) Is-kind-of, is-a, is-a-type-of

UIU Lecture 4a, CSI 211
3/12

Let A and B be classes

To determine if A should be the parent class of B ask:
Is B an A ( or is B a type of A, or is B a kind of A)

If the answer is yes, then B is in is-a relationship to A

Example# 1 - Bank Accounts


A J uni or Savi ngsAccount i s a t ype of a Savi ngsAccount



So, consi der maki ng J uni or Savi ngsAccount a subcl ass of Savi ngsAccount



Example# 2 - Employees


Consi der Empl oyee, Manager , Engi neer , and Fi l eCl er k



A Manager i s a ki nd of an Empl oyee.






cl ass Empl oyee
{
/ / st uf f not shown
}
cl ass Manager ext ends Empl oyee
{
/ / st uf f not shown
}



UIU Lecture 4a, CSI 211
4/12
b) is-analogous-to

If class X is-analogous-to class Y then look for superclass


Example BankAccounts

A checking account is analogous to a saving account


c) is-part-of or has-a

If class A is-part-of class B then there is no inheritance

Some negotiation between A and B for responsibilities may be needed
Example: Linked-List class and a Stack

A stack uses a linked-list in its implementation

A stack has a linked-list

The Stack class and the LinkedList class are separate classes



UIU Lecture 4a, CSI 211
5/12
cl ass Li nkedLi st
{
publ i c voi d addFr ont ( Obj ect i t em) { / / not shown}
publ i c Obj ect r emoveFr ont ( ) { / / not shown}
publ i c Obj ect r emoveEnd( ) { / / not shown}
}
cl ass St ack
{
Li nkedLi st st ackEl ement s = new Li nkedLi st ( ) ;
publ i c voi d push( Obj ect i t em)
{
st ackEl ement s. addFr ont ( i t em) ;
}
}

Interfaces

Let B & C be classes. Assume that we make A the parent class of B and C so A can hold
the methods and fields that are common between B and C.


Sometimes a method in B is so different from the same method in C there is no shared
implementation possible in A. We can make the method and A an abstract classes. The
methods in A then indicate which methods must be implemented in B and C. A can act as
type, which can hold objects of type B or C.

Sometimes all the methods of B must be implemented differently than the same method
in C. Make A an interface.

UIU Lecture 4a, CSI 211
6/12
Interfaces can specify public methods but can have no implementation of
methods.
Thus, one can not make an object from an interface.
Interfaces can have fields. All fields in an interface are final and static even if
they are not explicitly declared as such.
Interfaces have the same access levels as classes, public and package.
A class can implement more that one interface. If a parent class implements an
interface, its child classes automatically implement the interface.
An interface, like a class, defines a type. Fields, variables, and parameters can be
declared to be of a type defined by an interface.





Interface Example
This example shows the syntax of declaring an interface and a class implementing the
interface. The class must either implement all the methods in the interface or be an
abstract class.
a) Implementing all methods

publ i c i nt er f ace Door {
publ i c voi d open( ) ;
publ i c voi d cl ose( ) ;
}
publ i c cl ass Car Door i mpl ement s Door {
publ i c voi d open( ) {
Syst em. out . pr i nt l n( " Ent er t he car " ) ;
}
publ i c voi d cl ose( ) {
Syst em. out . pr i nt l n( " Look out , cl osi ng t he door " ) ;
}
}
cl ass Test Door {
publ i c st at i c voi d mai n( St r i ng[ ] ar gs ) {
Door aut omat i c = new Car Door ( ) ;
aut omat i c. open( ) ;
Car Door di r ect = new Car Door ( ) ;
di r ect . open( ) ;
}
}

Output
Ent er t he car
Ent er t he car

UIU Lecture 4a, CSI 211
7/12
b) Abstract Class implementation of Interface

This example shows a class that implements only some of the methods declared in an
interface. The class "CarDoor" must then be declared abstract. Objects can not be created
of the "CarDoor" class. A subclass must implement the missing method.
publ i c i nt er f ace Door {
publ i c voi d open( ) ;
publ i c voi d cl ose( ) ;
}
abst r act cl ass Car Door i mpl ement s Door {
publ i c voi d open( ) {
Syst em. out . pr i nt l n( " Ent er t he car " ) ;
}
}


All Interface Methods are Public

It is a compile error to declare a method as private or protected in an interface. Any
method without an access level in an interface is a public method. This can be confusing
so always declare methods in an interface as public.

Example # 1

publ i c i nt er f ace BadAccess {
publ i c voi d A( ) ;
pr ot ect ed voi d B( ) ; / / compi l e er r or
voi d C( ) ; / / l ooks l i ke package, but i s publ i c
pr i vat e voi d D( ) ; / / compi l e er r or
}


Example# 2
package whi t ney;
publ i c i nt er f ace GoodAccess {
publ i c voi d A( ) ;
voi d C( ) ;
}
package t est ;
i mpor t whi t ney. GoodAccess;
cl ass BadI mpl ement at i on i mpl ement s GoodAccess {
publ i c voi d A( ) {}
voi d C( ) {} / / Compi l e er r or , wr ong access l evel
}
cl ass GoodI mpl ement at i on i mpl ement s GoodAccess {
publ i c voi d A( ) {}
publ i c voi d C( ) {}
}


UIU Lecture 4a, CSI 211
8/12
Interfaces and Static Fields
Fields can be declared in an interface.
o All fields are public static and final.
o Declaring a field to be any other access level except public is a compile
error.
o If no access level is given, it defaults to public.
o If a field is not explicitly declared to be static or final, the field is still
static and final.
You may be tempted to use interfaces as a place to put program constants. Avoid
this. Usually a constant belongs to some abstraction. This abstraction should be
represented by a class. Place the constant in that class.
i nt er f ace Wi t hSt at i c {
publ i c st at i c f i nal i nt EXPLI CI T = 42;
publ i c st at i c i nt I S_FI NAL = 12;
publ i c i nt I S_FI NAL_AND_STATI C = 3;
pr ot ect ed i nt COMPI LE_ERROR = 4;

publ i c i nt NO_VALUE_COMPI LE_ERROR;
}
cl ass Radi o i mpl ement s Wi t hSt at i c {
publ i c voi d AM( ) {
Syst em. out . pr i nt l n( I S_FI NAL ) ;
}
}
cl ass Test {
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) {
Syst em. out . pr i nt l n( Wi t hSt at i c. EXPLI CI T ) ;
Syst em. out . pr i nt l n( Radi o. EXPLI CI T ) ;
Radi o megaBass = new Radi o( ) ;
Syst em. out . pr i nt l n( megaBass. EXPLI CI T ) ;
megaBass. AM( ) ;
}
}














UIU Lecture 4a, CSI 211
9/12
Extending Interfaces
One interface can inherit from another interface. Interfaces support multiple inheritance.
i nt er f ace Door {
publ i c voi d open( ) ;
publ i c voi d cl ose( ) ;
}
i nt er f ace Lockabl eDoor ext ends Door {
publ i c voi d l ock( ) ;
publ i c voi d unl ock( ) ;
}
cl ass Car Door i mpl ement s Lockabl eDoor {
pr i vat e bool ean i sLocked = f al se;
publ i c voi d open( ) {
i f ( ! i sLocked)
Syst em. out . pr i nt l n( " Ent er t he car " ) ;
}
publ i c voi d cl ose( ) {
Syst em. out . pr i nt l n( " Look out , cl osi ng t he door " ) ;
}

publ i c voi d l ock( ) { i sLocked = t r ue; }
publ i c voi d unl ock( ) { i sLocked = f al se; }
}
cl ass Test Door {
publ i c st at i c voi d mai n( St r i ng[ ] ar gs ) {
Door aut omat i c = new Car Door ( ) ;
aut omat i c. open( ) ;
aut omat i c. l ock( ) ; / / Compi l e er r or
Lockabl eDoor bet t er = ( Lockabl eDoor ) aut omat i c;
bet t er . l ock( ) ; / / OK
}
}




UIU Lecture 4a, CSI 211
10/12
Multiple Interfaces

A class can implement multiple interfaces. This example uses the LockableDoor and
Door interfaces from the last slide.

i nt er f ace Al ar m{
publ i c bool ean i sAl ar med( ) ;
publ i c voi d t ur nAl ar mOn( ) ;
publ i c voi d t ur nAl ar mOf f ( ) ;
}
cl ass Car Door i mpl ement s Lockabl eDoor , Al ar m{
pr i vat e bool ean i sLocked = f al se;
pr i vat e bool ean i sAl ar mOn = f al se;
publ i c bool ean i sAl ar med( ) {
r et ur n i sAl ar mOn;
}

publ i c voi d t ur nAl ar mOn( ) { i sAl ar mOn = t r ue; }

publ i c voi d t ur nAl ar mOf f ( ) { i sAl ar mOn = f al se; }

publ i c voi d open( ) {
i f ( i sAl ar mOn )
Syst em. out . pr i nt l n( " Sound t he al ar m" ) ;
el se i f ( ! i sLocked)
Syst em. out . pr i nt l n( " Ent er t he car " ) ;
}
publ i c voi d cl ose( ) {
Syst em. out . pr i nt l n( " Look out , cl osi ng t he door " ) ;
}
publ i c voi d l ock( ) { i sLocked = t r ue; }
publ i c voi d unl ock( ) { i sLocked = f al se; }
}

















UIU Lecture 4a, CSI 211
11/12
Interfaces and Inheritance
A class can implement multiple interfaces and extend one other class. This example uses
the LockableDoor, Door and Alarm interfaces from the last two slides.
cl ass Car Par t {
pr i vat e i nt par t I D;
pr i vat e f l oat wei ght ;
pr i vat e f l oat cost ;
publ i c voi d aMet hod( ) {
Syst em. out . pr i nt l n( " Thi s i s a car par t met hod" ) ;
}
}
cl ass Car Door ext ends Car Par t
i mpl ement s Lockabl eDoor , Al ar m{
pr i vat e bool ean i sLocked = f al se;
pr i vat e bool ean i sAl ar mOn = f al se;
publ i c bool ean i sAl ar med( ) {
r et ur n i sAl ar mOn;
}

publ i c voi d t ur nAl ar mOn( ) { i sAl ar mOn = t r ue; }

publ i c voi d t ur nAl ar mOf f ( ) { i sAl ar mOn = f al se; }

publ i c voi d open( ) {
i f ( i sAl ar mOn )
Syst em. out . pr i nt l n( " Sound t he al ar m" ) ;
el se i f ( ! i sLocked)
Syst em. out . pr i nt l n( " Ent er t he car " ) ;
}
publ i c voi d cl ose( ) {
Syst em. out . pr i nt l n( " Look out , cl osi ng t he door " ) ;
}
publ i c voi d l ock( ) { i sLocked = t r ue; }
publ i c voi d unl ock( ) { i sLocked = f al se; }
}






UIU Lecture 4a, CSI 211
12/12
Abstract Class vs Interface
An abstract method is a method that is declared without an implementation (without
braces, and followed by a semicolon), like this:
abst r act voi d moveTo( doubl e del t aX, doubl e del t aY) ;

If a class includes abstract methods, the class itself must be declared abst r act , as in:
publ i c abst r act cl ass Gr aphi cObj ect {
/ / decl ar e f i el ds
/ / decl ar e non- abst r act met hods
abst r act voi d dr aw( ) ;
}

We can not make i nst ance of Abst r act Cl ass as wel l as I nt er f ace.
Choosi ng i nt er f aces and abst r act cl asses i s not an ei t her / or
pr oposi t i on. I f you need t o change your desi gn, make i t an
i nt er f ace. However , you may have abst r act cl asses t hat pr ovi de
some def aul t behavi or . Abst r act cl asses ar e excel l ent candi dat es
i nsi de of appl i cat i on f r amewor ks.
i nt er f ace cont ai ns met hods t hat must be abst r act ; abst r act cl ass
may cont ai n concr et e met hods.
i nt er f ace cont ai ns var i abl es t hat must be st at i c and f i nal ;
abst r act cl ass may cont ai n non- f i nal and f i nal var i abl es.
member s i n an i nt er f ace ar e publ i c by def aul t , abst r act cl ass
may cont ai n non- publ i c member s.
i nt er f ace i s used t o " i mpl ement s" ; wher eas abst r act cl ass i s
used t o " ext ends" .
i nt er f ace can be used t o achi eve mul t i pl e i nher i t ance; abst r act
cl ass can be used as a si ngl e i nher i t ance.
i nt er f ace can " ext ends" anot her i nt er f ace, abst r act cl ass can
" ext ends" anot her cl ass and " i mpl ement s" mul t i pl e i nt er f aces.
i nt er f ace i s absol ut el y abst r act ; abst r act cl ass can be i nvoked
i f a mai n( ) exi st s.
i nt er f ace i s mor e f l exi bl e t han abst r act cl ass because one cl ass
can onl y " ext ends" one super cl ass, but " i mpl ement s" mul t i pl e
i nt er f aces.
I f gi ven a choi ce, use i nt er f ace i nst ead of abst r act cl ass.



*************** End of Lecture 4a **************

UIU Lecture 3b, CSI 211
1/9
United International University

Course: CSI 211
Course Title: Object Oriented Programming
Lecture 4b: Clone And Collections


Clone

J ava has a mechanism to allow objects to be copied using clone method.

A class must:
State it implements Cloneable to use the mechanism
Implement the clone method
For the default clone behavior, all the clone method has to do is return
super.clone()
clone() is not the same as "new"
clone() copies the values of the fields an object
The clone process does not call either a constructor or any initialization blocks of
the cloned object's class.



UIU Lecture 3b, CSI 211
2/9
Using the Default Clone Process
This example shows the minimum effort needed to support the clone method. We will
cover exceptions (the throws CloneNotSupportedException) in later lectures.
publ i c cl ass Sampl e i mpl ement s Cl oneabl e {
pr i vat e i nt si ze = 0;

publ i c voi d set Si ze( i nt newSi ze ) { si ze = newSi ze; }

publ i c St r i ng t oSt r i ng( ) {
r et ur n " Si ze: " + si ze;
}

publ i c Obj ect cl one( ) t hr ows Cl oneNot Suppor t edExcept i on {
r et ur n super . cl one( ) ;
}
}
publ i c cl ass Test {
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
t hr ows Cl oneNot Suppor t edExcept i on {
Sampl e a = new Sampl e( ) ;
Sampl e b = ( Sampl e) a. cl one( ) ;
a. set Si ze( 12 ) ;
Syst em. out . pr i nt l n( " a " + a ) ;
Syst em. out . pr i nt l n( " b " + b ) ;
}
}
Output
a Si ze: 12
b Si ze: 0



clone() is not "new"

This example demonstrates that when you clone an object constructors and initialization
block are not called. While not shown here, direct assignments in fields are also not done
when cloning objects as they are done when you create an object via "new".

publ i c cl ass Cl oneI sNot New i mpl ement s Cl oneabl e {
{
Syst em. out . pr i nt l n( " I n i nst ance i ni t i al i zat i on bl ock" ) ;
}

publ i c Cl oneI sNot New( ) {
Syst em. out . pr i nt l n( " I n const r uct or " ) ;
}

publ i c Obj ect cl one( ) {
r et ur n super . cl one( ) ;
}

UIU Lecture 3b, CSI 211
3/9
}
publ i c cl ass Test {
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) t hr ows Except i on {
Cl oneI sNot New a = new Cl oneI sNot New( ) ;
Syst em. out . pr i nt l n( " St ar t cl one" ) ;
Cl oneI sNot New b = ( Cl oneI sNot New) a. cl one( ) ;
Cl oneI sNot New c = ( Cl oneI sNot New) a. cl one( ) ;
}
}

Output
I n i nst ance i ni t i al i zat i on bl ock
I n const r uct or
St ar t cl one



Problems with Default clone()

The default clone method clones the reference but not object or array that is referenced

Using the default clone on an object with a field that is a reference results in two objects
with references to the same item. Let Wrapper be a class that has a field, which is a
reference to another object. For this example, the other object as a field of type int. Using
the default clone process we get two wrapper objects, a and b, which both reference the
same object. Any change in the state of this object will be visible through both objects a
and b.
Wr apper a = new Wr apper ( ) ;


Wr apper b = ( Wr apper ) a. cl one( ) ;






UIU Lecture 3b, CSI 211
4/9
Using Default clone with Field References

In this example, the class "BadWrapper" has a field that is a reference to a "Sample"
object. The class "BadWrapper" uses the default clone process. In class
"TestBadWrapper" a "BadWrapper" object is cloned. Now two "BadWrapper" objects
reference the same "Sample" object.
publ i c cl ass Sampl e i mpl ement s Cl oneabl e {
pr i vat e i nt si ze = 0;

publ i c voi d set Si ze( i nt newSi ze ) { si ze = newSi ze; }

publ i c St r i ng t oSt r i ng( ) { r et ur n " Si ze: " + si ze; }

publ i c Obj ect cl one( ) {
r et ur n super . cl one( ) ;
}
}
publ i c cl ass BadWr apper i mpl ement s Cl oneabl e {
pr i vat e Sampl e aRef er ence =new Sampl e( ) ;

publ i c voi d set Si ze( i nt newSampl eSi ze ) {
aRef er ence. set Si ze( newSampl eSi ze ) ;
}

publ i c St r i ng t oSt r i ng( ) {
r et ur n " Wr apper " + aRef er ence. t oSt r i ng( ) ;
}

publ i c Obj ect cl one( ) {
r et ur n super . cl one( ) ;
}
}

Note that the state of "a" is changed, but when we print out "a" and "b", they have the
same state. This is because they reference the same "Sample" object.
publ i c cl ass Test BadWr apper
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) t hr ows Except i on
{
BadWr apper a = new BadWr apper ( ) ;
BadWr apper b = ( BadWr apper ) a. cl one( ) ;
a. set Si ze( 12 ) ;
Syst em. out . pr i nt l n( " a " + a ) ;
Syst em. out . pr i nt l n( " b " + b ) ;
}
}

Output
a Wr apper Si ze: 12
b Wr apper Si ze: 12



UIU Lecture 3b, CSI 211
5/9
Resolving Cloning Object References
In this example the field "aReference" is explicitly cloned in the clone method. Now
when we clone GoodWrapper objects, each object has its own copies of "Sample" object.
publ i c cl ass GoodWr apper i mpl ement s Cl oneabl e {
pr i vat e Sampl e aRef er ence =new Sampl e( ) ;

publ i c voi d set Si ze( i nt newSampl eSi ze ) {
aRef er ence. set Si ze( newSampl eSi ze ) ;
}

publ i c St r i ng t oSt r i ng( ) {
r et ur n " Wr apper " + aRef er ence. t oSt r i ng( ) ;
}

publ i c Obj ect cl one( ) t hr ows Cl oneNot Suppor t edExcept i on {
GoodWr apper cl one = ( GoodWr apper ) super . cl one( ) ;
cl one. aRef er ence = ( Sampl e) aRef er ence. cl one( ) ;
r et ur n cl one;
}
}
publ i c cl ass Test {
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) t hr ows Except i on {
GoodWr apper a = new GoodWr apper ( ) ;
GoodWr apper b = ( GoodWr apper ) a. cl one( ) ;
a. set Si ze( 12 ) ;
Syst em. out . pr i nt l n( " a " + a ) ;
Syst em. out . pr i nt l n( " b " + b ) ;
}
}
Output
a Wr apper Si ze: 12
b Wr apper Si ze: 0



UIU Lecture 3b, CSI 211
6/9
Cloning Arrays

If we have an array of basic types, then the array must be cloned if we do not want the
same array referenced in two or more objects. This example shows one way to clone an
array.
publ i c cl ass Ar r ayWr apper i mpl ement s Cl oneabl e {
pr i vat e i nt [ ] aRef er ence = { 0 };

publ i c voi d set Si ze( i nt newSampl eSi ze ) {
aRef er ence[ 0] = newSampl eSi ze;
}

publ i c St r i ng t oSt r i ng( ) {r et ur n " Wr apper " + aRef er ence[ 0] ; }

publ i c Obj ect cl one( ) t hr ows Cl oneNot Suppor t edExcept i on {
Ar r ayWr apper cl one = ( Ar r ayWr apper ) super . cl one( ) ;
cl one. aRef er ence = ( i nt [ ] ) aRef er ence. cl one( ) ;
r et ur n cl one;
}
}
publ i c cl ass Test {
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) t hr ows Except i on {
Ar r ayWr apper a = new Ar r ayWr apper ( ) ;
Ar r ayWr apper b = ( Ar r ayWr apper ) a. cl one( ) ;
a. set Si ze( 12 ) ;
Syst em. out . pr i nt l n( " a " + a ) ;
Syst em. out . pr i nt l n( " b " + b ) ;
}
}
Output
a Wr apper 12
b Wr apper 0


Java Collections

Col l ect i ons ar e obj ect s t hat hol d ot her obj ect s t hat ar e accessed,
pl aced, and mai nt ai ned under some set of r ul es.
Exampl es
Set s
Li st
Map







UIU Lecture 3b, CSI 211
7/9

List

Li st i s an i nt er f ace but The Ar r ayLi st cl ass i s a concr et e
i mpl ement at i on of Li st i nt er f ace. Thi s cl ass suppor t s dynami c ar r ays
t hat can gr ow as needed.


public class Ar ar yLi st Demo {

public static void mai n( St r i ng[ ] ar gs) {

Ar r ayLi st al = new Ar r ayLi st ( ) ;
Syst em. out . pr i nt ( " I ni t i al si ze of al : " + al . si ze( ) ) ;
Syst em. out . pr i nt ( " \ n" ) ;

/ / add. el ement s t o t he ar r ay l i st
al . add( " C" ) ;
al . add( " A" ) ;
al . add( " E" ) ;
al . add( " B" ) ;
al . add( " D" ) ;
al . add( " F" ) ;
al . add( 1, " A2" ) ; / / i nser t s obj ect s " A2" i nt o ar r ay at i ndex 1

Syst em. out . pr i nt ( " si ze of al af t er addi t i ons " + al . si ze( ) ) ;
Syst em. out . pr i nt ( " \ n" ) ;

/ / di spl ay t he ar r ay l i st
Syst em. out . pr i nt ( " cont ent s of al : " + al ) ;
Syst em. out . pr i nt ( " \ n" ) ;

/ / Remove el ement s f r omt he ar r ay l i st
al . r emove( " F" ) ;
al . r emove( 2) ;

Syst em. out . pr i nt ( " si ze of af t er del et i ons : " + al . si ze( ) ) ;
Syst em. out . pr i nt ( " \ n" ) ;
Syst em. out . pr i nt ( " cont ent s of al : " + al ) ;

}

}
Output Screen:
I ni t i al si ze of al : 0
si ze of al af t er addi t i ons 7
cont ent s of al : [ C, A2, A, E, B, D, F]
si ze of af t er del et i ons : 5
cont ent s of al : [ C, A2, E, B, D]





UIU Lecture 3b, CSI 211
8/9
Iterator

Iterators are used to access the elements of an aggregate object sequentially without
exposing its underlying representation.

I t er at or i t = set . i t er at or ( ) ;
whi l e ( i t . hasNext ( ) ) {
/ / Get el ement
Obj ect el ement = i t . next ( ) ;
}

b) Map

Map is an object that stores key/volume pairs.
Given a key, you can find its value. Keys must be unique, but values may be
duplicated.
The HashMap class provides the primary implementation of the map interface.


public class HashMapDemo {

public static void mai n( St r i ng[ ] ar gs) {

HashMap hm= new HashMap( ) ;
hm. put ( " Rohi t " , new Doubl e( 3434. 34) ) ;
hm. put ( " Mohi t " , new Doubl e( 123. 22) ) ;
hm. put ( " Ashi sh" , new Doubl e( 1200. 34) ) ;
hm. put ( " Khar i wal " , new Doubl e( 99. 34) ) ;
hm. put ( " Pankaj " , new Doubl e( - 19. 34) ) ;
Set set = hm. ent r ySet ( ) ;

I t er at or i = set . i t er at or ( ) ;

while( i . hasNext ( ) ) {
Map. Ent r y me = ( Map. Ent r y) i . next ( ) ;
Syst em. out . pr i nt l n( me. get Key( ) + " : " + me. get Val ue( ) ) ;
}

/ / deposi t i nt o Rohi t ' s Account
double bal ance = ( ( Doubl e) hm. get ( " Rohi t " ) ) . doubl eVal ue( ) ;
hm. put ( " Rohi t " , new Doubl e( bal ance + 1000) ) ;

Syst em. out . pr i nt l n( " Rohi t new bal ance : " + hm. get ( " Rohi t " ) ) ;

}
}


UIU Lecture 3b, CSI 211
9/9
Output Screen:
Rohi t : 3434. 34
Ashi sh : 1200. 34
Pankaj : - 19. 34
Mohi t : 123. 22
Khar i wal : 99. 34
Rohi t new bal ance : 4434. 34





*************** End of Lecture 4b **************

UIU Lecture 5a, CSI 211
1/10
United International University

Course: CSI 211
Course Title: Object Oriented Programming
Lecture 5a: Exception Handling.


Exceptions
An exception i s an event , whi ch occur s dur i ng t he execut i on of a
pr ogr am, t hat di sr upt s t he nor mal f l ow of t he pr ogr am' s
i nst r uct i ons.
I n J ava al l except i ons ar e i nst ances of j ava. l ang. Except i on or
one of i t s subcl asses.

cl ass Di f f i cul t Except i on ext ends Except i on {
publ i c Di f f i cul t Except i on ( ) {
super ( ) ;
}
publ i c Di f f i cul t Except i on ( St r i ng er r or Message ) {
super ( er r or Message ) ;
}
}

How it occurs?



a) Implicitly by some error condition

cl ass I mpl i ci t l yRai sedExcept i on
{
publ i c st at i c voi d mai n( St r i ng[ ] ar gument s )
{
i nt st udent s[ ] = new i nt [ 5] ;
st udent s[ 10 ] = 1; / / Except i on occur s her e


b) Explicitly by the Programmer

cl ass Expl i ci t l yRai sedExcept i on
{
publ i c st at i c voi d mai n( St r i ng[ ] ar gument s )
{
t hr ow new Ar r ayI ndexOut Of BoundsExcept i on( ) ;
}
}
Handling an Exception

UIU Lecture 5a, CSI 211
2/10


Use t r y- cat ch bl ock.


cl ass Ar r ayOut Of Bounds
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
i nt st udent s[ ] = new i nt [ 5] ;
t r y
{
Syst em. out . pr i nt l n( " St ar t Tr y" ) ;
st udent s[ 10 ] = 1;
Syst em. out . pr i nt l n( " Af t er assi gnment st at ement " ) ;
}
/ / cat ch i s t he handl er
cat ch ( Ar r ayI ndexOut Of BoundsExcept i on e)
{
Syst em. er r . pr i nt l n( " Out Of Bounds: " + e. get Message( ) ) ;
}
Syst em. out . pr i nt l n( " Af t er t r y " ) ;
}
}
Output
St ar t Tr y
Out Of Bounds: 10
Af t er t r y


try-catch must be together

try and catch are not separate blocks
try and catch are one construct
Case #1
cl ass NeedCat chWi t hTr yBl ock
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
i nt st udent s[ ] = new i nt [ 5] ;
t r y
{
Syst em. out . pr i nt l n( " St ar t Tr y" ) ;
st udent s[ 10 ] = 1;
Syst em. out . pr i nt l n( " Af t er assi gnment st at ement " ) ;
}
Syst em. out . pr i nt l n( " Af t er t r y " ) ; / / Compi l e er r or
}
}



Case #2


UIU Lecture 5a, CSI 211
3/10
publ i c cl ass CanNot HaveCodeBet weenTr yAndCat ch
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
i nt st udent s[ ] = new i nt [ 5] ;
t r y
{
Syst em. out . pr i nt l n( " St ar t Tr y" ) ;
st udent s[ 10 ] = 1;
Syst em. out . pr i nt l n( " Af t er assi gnment st at ement " ) ;
}
i nt Dont HaveCodeHer e = 5 / 32; / / Er r or her e
/ / cat ch i s t he handl er
cat ch ( Ar r ayI ndexOut Of BoundsExcept i on e)
{
Syst em. er r . pr i nt l n( " Out Of Bounds: " + e. get Message( ) ) ;
}
Syst em. out . pr i nt l n( " Af t er t r y " ) ;
}
}


Exception Methods

i nher i t ed f r omThr owabl e


publ i c cl ass Except i onMet hods {
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) t hr ows Except i on {

t r y {
t est Cal l ( ) ;
} cat ch ( Bor i ngLect ur eExcept i on aLect ur e ) {
aLect ur e. pr i nt St ackTr ace( ) ;
}
}
publ i c st at i c voi d t est Cal l ( ) t hr ows Bor i ngLect ur eExcept i on {
t hr ow new Bor i ngLect ur eExcept i on( " Hel l o t est i ng" ) ;
}
}
cl ass Bor i ngLect ur eExcept i on ext ends Except i on {
publ i c Bor i ngLect ur eExcept i on( ) { super ( ) ; }
publ i c Bor i ngLect ur eExcept i on( St r i ng er r or Message ) {
super ( er r or Message ) ;
}
}
Output
Bor i ngLect ur eExcept i on: Hel l o t est i ng
at Except i onMet hods. t est Cal l ( Except i onMet hods. j ava)
at Except i onMet hods. mai n( Except i onMet hodsj ava)


Types of Exceptions

UIU Lecture 5a, CSI 211
4/10


a) Checked Exception
o Here the method throws the exception and the client code handle it.



publ i c voi d st or eDat aFr omUr l ( St r i ng ur l ) {

/ / cl i ent code handl i ng t hi s
t r y {
St r i ng dat a = r eadDat aFr omUr l ( ur l ) ;
} cat ch ( BadUr l Except i on e) {
e. pr i nt St ackTr ace( ) ;
}
}

publ i c St r i ng r eadDat aFr omUr l ( St r i ng ur l )
t hr ows BadUr l Except i on{ / / met hod t hr ows except i on
i f ( i sUr l Bad( ur l ) ) {
t hr ow new BadUr l Except i on( " Bad URL: " + ur l ) ;
}

St r i ng dat a = nul l ;
/ / r ead l ot s of dat a over HTTP and r et ur n
/ / i t as a St r i ng i nst ance.

r et ur n dat a;
}




b) UnChecked Exception

Her e t he met hod does not t hr ow except i on. The met hod handl e t he
except i on.

publ i c cl ass Fi ndHandl er Si mpl eExampl e
{
publ i c st at i c voi d change( i nt [ ] cour se ) / / does not t hr ow excpt
{
Syst em. out . pr i nt l n( " St ar t Change" ) ;
cour se[ 10 ] = 1;
Syst em. out . pr i nt l n( " End Change" ) ;
}
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
i nt st udent s[ ] = new i nt [ 5] ;
t r y
{
Syst em. out . pr i nt l n( " St ar t Tr y" ) ;
change( st udent s ) ;
Syst em. out . pr i nt l n( " Af t er change" ) ;
}
cat ch ( Ar r ayI ndexOut Of BoundsExcept i on e)

UIU Lecture 5a, CSI 211
5/10
{
Syst em. er r . pr i nt l n( " Out Of Bounds: " + e. get Message( ) ) ;
}
Syst em. out . pr i nt l n( " Af t er t r y " ) ;
}
}
Output
St ar t Tr y
St ar t Change
Out Of Bounds: 10
Af t er t r y


Unchecked Exception - Multiple try-catches

Once an exception is handled, the program continues normal execution after the try-catch
block. Although this program has two try-catches for the
ArrayIndexOutOfBoundsException, only the first is used.
publ i c cl ass Fi ndHandl er TwoTr yBl ocks {
publ i c st at i c voi d change( i nt [ ] cour se ) {
t r y{
Syst em. out . pr i nt l n( " St ar t Change" ) ;
cour se[ 10 ] = 1;
Syst em. out . pr i nt l n( " End Change" ) ;
} cat ch ( Ar r ayI ndexOut Of BoundsExcept i on e) {
Syst em. er r . pr i nt l n( " Change Cat ch: " + e. get Message( ) ) ;
}
}
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) {
i nt st udent s[ ] = new i nt [ 5] ;
t r y {
Syst em. out . pr i nt l n( " St ar t Tr y" ) ;
change( st udent s ) ;
Syst em. out . pr i nt l n( " Af t er change" ) ;
} cat ch ( Ar r ayI ndexOut Of BoundsExcept i on e) {
Syst em. er r . pr i nt l n( " Mai n Cat ch: " + e. get Message( ) ) ;
}
Syst em. out . pr i nt l n( " Af t er t r y " ) ;
}
}
Output
St ar t Tr y
St ar t Change
Change Cat ch: 10
Af t er change
Af t er t r y






Unchecked Exceptions - No try-catch

UIU Lecture 5a, CSI 211
6/10

As many of you have already found out, if there is no try-catch in your program, the
J VM's try-catch catches the exception, prints out the stack trace, then exits.
publ i c cl ass NoHandl er
{
publ i c st at i c voi d change( i nt [ ] cour se )
{
Syst em. out . pr i nt l n( " St ar t Change" ) ;
cour se[ 10 ] = 1;
Syst em. out . pr i nt l n( " End Change" ) ;
}
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
i nt st udent s[ ] = new i nt [ 5] ;
Syst em. out . pr i nt l n( " St ar t Tr y" ) ;
change( st udent s ) ;
Syst em. out . pr i nt l n( " Af t er change" ) ;
}
}
Output
St ar t Tr y
St ar t Change
j ava. l ang. Ar r ayI ndexOut Of BoundsExcept i on: 10
at NoHandl er . mai n( NoHandl er . j ava)



UIU Lecture 5a, CSI 211
7/10

J AVA I / O



a) Reader

FileReader

A simple example of using a Reader. In this case, it is a FileReader.

cl ass Count Si ze
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) t hr ows I OExcept i on,
Fi l eNot FoundExcept i on
{
t r y
{
Reader i n = new Fi l eReader ( " Exam" ) ;

i nt t ot al ;

f or ( t ot al = 0; i n. r ead( ) ! = - 1; t ot al ++)
;
Syst em. out . pr i nt l n( t ot al ) ;
}
cat ch ( Fi l eNot FoundExcept i on f i l ePr obl em)
{
Syst em. er r . pr i nt l n( " Fi l e not f ound" ) ;
t hr ow f i l ePr obl em;
}
cat ch ( I OExcept i on i oPr obl em)
{
Syst em. er r . pr i nt l n( " I O pr obl em" ) ;
t hr ow i oPr obl em;
}
}
}
Output
7428



UIU Lecture 5a, CSI 211
8/10
FileInputStream
publ i c cl ass MyFi r st Fi l eReadi ngApp
{
/ / Mai n met hod
publ i c st at i c voi d mai n ( St r i ng ar gs[ ] )
{
/ / St r eamt o r ead f i l e
Fi l eI nput St r eamf i n;

t r y
{
/ / Open an i nput st r eam
f i n = new Fi l eI nput St r eam( " myf i l e. t xt " ) ;

/ / Read a l i ne of t ext
Syst em. out . pr i nt l n( new
Dat aI nput St r eam( f i n) . r eadLi ne( ) ) ;

/ / Cl ose our i nput st r eam
f i n. cl ose( ) ;
}
/ / Cat ches any er r or condi t i ons
cat ch ( I OExcept i on e)
{
Syst em. er r . pr i nt l n ( " Unabl e t o r ead f r omf i l e" ) ;
Syst em. exi t ( - 1) ;
}
}
}
b) Writer
FileWriter.

cl ass Capi t al i ze
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) t hr ows I OExcept i on
{
Reader i n = new St r i ngReader ( " abcdef ghi j " ) ;
Wr i t er out = new Fi l eWr i t er ( " Exampl e" ) ;

i nt next Char ;

whi l e ( ( next Char = i n. r ead( ) ) ! = - 1 )
out . wr i t e( Char act er . t oUpper Case( ( char ) next Char ) ) ;
out . wr i t e( ' \ n' ) ;
out . f l ush( ) ; / / not needed bef or e a cl ose
out . cl ose( ) ; / / exi t i ng pr ogr amcl oses t he Wr i t er

UIU Lecture 5a, CSI 211
9/10
}
}
Output
ABCDEFGHI J
PrintWriter
PrintWriter contains higher level output methods to write data. Print() and println() send
the toString() method to objects.

cl ass EasyPr i nt
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) t hr ows I OExcept i on
{
Wr i t er out = new Fi l eWr i t er ( " Let t er Home" ) ;
Pr i nt Wr i t er easyOut = new Pr i nt Wr i t er ( out ) ;
easyOut . pr i nt l n( " Hi t her e" ) ;
easyOut . pr i nt l n( 5 ) ;
easyOut . pr i nt l n( t r ue ) ;
easyOut . cl ose( ) ;
}
}
Output File
Hi Mom
5
t r ue

OutputStream Example



cl ass Count Si ze
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) t hr ows I OExcept i on
{
I nput St r eami n;
i n = new St r i ngBuf f er I nput St r eam( " abcdef ghi j " ) ;
Out put St r eamout = Syst em. out ;

i nt next Char ;

whi l e ( ( next Char = i n. r ead( ) ) ! = - 1 )
out . wr i t e( Char act er . t oUpper Case( ( char ) next Char ) ) ;
out . wr i t e( ' \ n' ) ;
out . f l ush( ) ;
}

UIU Lecture 5a, CSI 211
10/10
}

Output
ABCDEFGHI J

FileOutputStream

publ i c cl ass MyFi r st Fi l eWr i t i ngApp
{
/ / Mai n met hod
publ i c st at i c voi d mai n ( St r i ng ar gs[ ] )
{
/ / St r eamt o wr i t e f i l e
Fi l eOut put St r eamf out ;

t r y
{
/ / Open an out put st r eam
f out = new Fi l eOut put St r eam( " myf i l e. t xt " ) ;

/ / Pr i nt a l i ne of t ext
new Pr i nt St r eam( f out ) . pr i nt l n ( " hel l o wor l d! " ) ;

/ / Cl ose our out put st r eam
f out . cl ose( ) ;
}
/ / Cat ches any er r or condi t i ons
cat ch ( I OExcept i on e)
{
Syst em. er r . pr i nt l n ( " Unabl e t o wr i t e t o f i l e" ) ;
Syst em. exi t ( - 1) ;
}
}
}





*************** End of Lecture 5a **************

UIU Lecture 5b, CSI 211
1/7
United International University

Course: CSI 211
Course Title: Object Oriented Programming
Lecture 5b: Nested and Inner Classes.


Nested Classes
J ava programming language allows you to define a class within another class.
Such a class is called a nested class and is illustrated here:

class OuterClass {
...
class NestedClass {
...
}
}

Why Use Nested Classes?
There are several compelling reasons for using nested classes, among them:
It is a way of logically grouping classes that are only used in one place.
It increases encapsulation.
Nested classes can lead to more readable and maintainable code.

Nest ed cl asses ar e di vi ded i nt o t wo cat egor i es: st at i c and non-
st at i c. Nest ed cl asses t hat ar e decl ar ed st at i c ar e si mpl y cal l ed
static nested classes. Non- st at i c nest ed cl asses ar e cal l ed inner
classes.


static nested classes

Static nested classes are accessed using the enclosing class name:
Out er Cl ass. St at i cNest edCl ass



cl ass Out er Cl ass {
. . .

UIU Lecture 5b, CSI 211
2/7
st at i c cl ass St at i cNest edCl ass {
. . .
}
cl ass I nner Cl ass {
. . .
}
}

Example

publ i c cl ass Out Si de {
pr i vat e St r i ng name = " Roger " ;

publ i c st at i c cl ass Nest ed {
pr i vat e i nt si ze;

publ i c Nest ed( i nt si ze ) {
t hi s. si ze = si ze;
}

publ i c voi d pr i nt ( ) {
Syst em. out . pr i nt l n( " Nest ed " + si ze ) ;
}
}

publ i c voi d pr i nt ( ) {
Syst em. out . pr i nt l n( " Out si de " + name ) ;
( new Nest ed( 10 ) ) . pr i nt ( ) ;
}
}
publ i c cl ass Test Nest ed {
publ i c st at i c voi d mai n( St r i ng[ ] ar gument s) {
Out Si de pi t ch = new Out Si de( ) ;
pi t ch. pr i nt ( ) ;
Out Si de. Nest ed a = new Out Si de. Nest ed( 5 ) ;
a. pr i nt ( ) ;
}
}

Output
Out si de Roger
Nest ed 10
Nest ed 5


UIU Lecture 5b, CSI 211
3/7
Inner classes

Obj ect s t hat ar e i nst ances of an i nner cl ass exi st within an
i nst ance of t he out er cl ass.









cl ass Out er Cl ass {
. . .
cl ass St at i cNest edCl ass {
. . .
}
cl ass I nner Cl ass {
. . .
}
}


Example#1

public class Out Si de {
private St r i ng name = " Roger " ;

public class Nest ed {
private int si ze;

public Nest ed( int si ze ) {
this. si ze = si ze;
}

public void pr i nt ( ) {
Syst em. out. pr i nt l n( " Nest ed " + si ze ) ;
}
}

public void pr i nt ( ) {
Syst em. out. pr i nt l n( " Out si de " + name ) ;
( new Nest ed( 10 ) ) . pr i nt ( ) ;
}
}




UIU Lecture 5b, CSI 211
4/7
public class Test Nest ed {
public static void mai n( St r i ng[ ] ar gument s) {
Out Si de pi t ch = new Out Si de( ) ;
pi t ch. pr i nt ( ) ;
Out Si de. Nest ed a = pi t ch. new Nest ed( 5 ) ;
a. pr i nt ( ) ;
}
}


Example#2

publ i c cl ass Dat aSt uf f {
pr i vat e i nt si ze = 0;

publ i c cl ass Count er {

publ i c voi d i ncr ease( ) {
si ze++; / / accessi ng encl osi ng cl asses pr i vat e f i el d
}
}/ / cl ass Count er

publ i c St r i ng t oSt r i ng( ) {
r et ur n St r i ng. val ueOf ( si ze) ;
}

publ i c Count er get Count er ( ) {
r et ur n new Count er ( ) ;
}
}/ / cl ass Dat aSt uf f
publ i c cl ass Test {
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) {
Dat aSt uf f a = new Dat aSt uf f ( ) ;
Dat aSt uf f b = new Dat aSt uf f ( ) ;
Dat aSt uf f . Count er count er A = a. get Count er ( ) ;
Dat aSt uf f . Count er count er B = b. new Count er ( ) ;
count er A. i ncr ease( ) ;
count er A. i ncr ease( ) ;
count er B. i ncr ease( ) ;
Syst em. out . pr i nt l n( " A " + a + " B " + b ) ;
}
}

Output
A 2 B 1


Inner Classes & this

"this" in a innerr class refers to the current object. It can be used to refer to fields and
methods of the current object. "this" can not be used to refer to fields and method of the
enclosing class.
publ i c cl ass Dat aSt uf f {
pr i vat e i nt si ze = 0;

UIU Lecture 5b, CSI 211
5/7

publ i c cl ass Count er {
publ i c voi d i ncr ease( ) {
t hi s. si ze++; / / Compi l e er r or
}
}/ / cl ass Count er
}

To refer to the enclosing class use ClassName.this

publ i c cl ass Dat aSt uf f {
pr i vat e i nt si ze = 0;

publ i c cl ass Count er {

publ i c voi d i ncr ease( ) {
Dat aSt uf f . t hi s. si ze++;
}
}/ / cl ass Count er
}



Another example of using the className.this to access enclosing class fields
publ i c cl ass A {
St r i ng name = " A" ;

publ i c cl ass B {
St r i ng name = " B" ;

publ i c cl ass C {
St r i ng name = " C" ;

publ i c voi d pr i nt ( St r i ng name ) {
Syst em. out . pr i nt l n( name ) ; / / pr i nt s t he ar gument
Syst em. out . pr i nt l n( t hi s. name ) ; / / C
Syst em. out . pr i nt l n( C. t hi s. name ) ; / / C
Syst em. out . pr i nt l n( B. t hi s. name ) ; / / B
Syst em. out . pr i nt l n( A. t hi s. name ) ; / / A
}
}
}
}



UIU Lecture 5b, CSI 211
6/7
Local Classes

A local class is a class declared in within a block of code
A local class is visible and usable within the block of code in which it is defined



publ i c cl ass TopLevel {
pr i vat e i nt si ze = 0;

publ i c i nt pr ocess( f i nal i nt i nput ) {
cl ass Hel per { / / Hel per i s a l ocal cl ass
i nt l ocal Si ze;
publ i c Hel per ( i nt si zeI n ) {
l ocal Si ze = si zeI n;
}
publ i c i nt usef ul ( ) {
r et ur n i nput + l ocal Si ze;
}

}/ / Cl ass Hel per
Hel per myFr i end = new Hel per ( si ze) ;
r et ur n myFr i end. usef ul ( ) ;
} / / pr ocess
} / / cl ass TopLevel



Numeric Classes



The numeric classes provide an object wrapper for numeric data values and serves as a
place for numeric-oriented operations.

cl ass Numer i cCl assesExampl e
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
I nt eger hei ght = new I nt eger ( 10 ) ;

UIU Lecture 5b, CSI 211
7/7
I nt eger wi dt h = new I nt eger ( 25 ) ;
I nt eger dept h = 25; / / Compi l e er r or
I nt eger ar ea;
ar ea = hei ght * wi dt h; / / Compi l e er r or
ar ea = new I nt eger ( hei ght . i nt Val ue( ) * wi dt h. i nt Val ue( ) ) ;
Syst em. out . pr i nt l n( ar ea ) ;
St r i ng ar eaAsSt r i ng = ar ea. t oSt r i ng( ) ;
i nt ar eaAsI nt = ar ea. i nt Val ue( ) ;
l ong ar eaAsLong = ar ea. l ongVal ue( ) ;
Syst em. out . pr i nt l n( I nt eger . MAX_VALUE ) ;
}
}


How t o use?
publ i c cl ass Test {
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) t hr ows Except i on {

i nt i nt Sampl e = 4;
St r i ng i nt Sampl eBi t s = I nt eger . t oBi nar ySt r i ng( i nt Sampl e ) ;
St r i ng i nt Sampl eHex = I nt eger . t oHexSt r i ng( i nt Sampl e ) ;
Syst em. out . pr i nt l n( " " + i nt Sampl e + " i n bi t s " + i nt Sampl eBi t s
) ;
Syst em. out . pr i nt l n( " " + i nt Sampl e + " i n Hex " + i nt Sampl eHex) ;
f l oat Sampl e = 4. 4F;
f l oat Sampl eBi t s =
I nt eger . t oBi nar ySt r i ng( Fl oat . f l oat ToI nt Bi t s( f l oat Sampl e ) ) ;
f l oat Sampl eHex =
I nt eger . t oHexSt r i ng( Fl oat . f l oat ToI nt Bi t s( f l oat Sampl e ) ) ;
Syst em. out . pr i nt l n( " " + f l oat Sampl e + " i n bi t s " +
f l oat Sampl eBi t s) ;
}
}
Output
4 i n bi t s 100
4 i n Hex 4
4. 4 i n bi t s 1000000100011001100110011001101











*************** End of Lecture 5b **************

UIU Lecture 6b, CSI 211
1/6
United International University

Course: CSI 211
Course Title: Object Oriented Programming
Lecture 7a: Threads

Concurrent Programming
Di f f er ent par t s of t he same pr ogr amcan be execut i ng at t he same
t i me, or behave i f t hey ar e execut i ng at t he same t i me.
J ava uses t hr eads t o achi eve concur r ency.
Wr i t i ng concur r ent pr ogr ams pr esent s a number of i ssues t hat do
not occur i n wr i t i ng sequent i al code.

I ssues I nvol ve i n Concur r ent Pr ogr ammi ng

Safety
Two different threads could write to the same memory location at the same time, leaving
the memory location in an improper state.

Liveness
Threads can become deadlocked, each thread waiting forever for the other to perform a
task. Threads can become livelocked, waiting forever to get their turn to execute.

Nondeterminism
Thread activities can become intertwined. Different executions of a program with the
same input can produce different results. This can make program hard to debug.

Communication
Di f f er ent t hr eads i n t he same pr ogr amexecut e aut onomousl y f r omeach
ot her . Communi cat i on bet ween t hr eads i s an i ssue.





UIU Lecture 6b, CSI 211
2/6
Threads

A t hr ead i s a f l ow of execut i on
A thread i s an act i ve ent i t y t hat shar es t he same name space as
t he pr ogr amt hat cr eat ed t he t hr ead. Thi s means t hat t wo t hr eads
i n a pr ogr amcan access t he same dat a.










UIU Lecture 6b, CSI 211
3/6
Creating Threads
There are two different methods for creating a thread:
extending the Thread class or
implementing the Runnable interface.

i) Extending the Thread class
In the Thread subclass, implement the run() method. The signature of run() must
be as it is in this example. run() is the entry point or starting point (or main) of
your thread.
To start a thread, create an object from your Thread class. Send the "start()"
method to the thread object. This will create the new thread, start it as an active
entity in your program, and call the run() method in the thread object.
Do not call the run() method directly. Calling the run() directly executes the
method in the normal sequential manner.
cl ass Si mpl eThr ead ext ends Thr ead {
publ i c voi d r un( ) {
f or ( i nt count = 0; count < 4; count ++)
Syst em. out . pr i nt l n( " Message " + count +
" Fr om: A" ) ;
}
}
cl ass Test i ngSi mpl eThr ead {
publ i c st at i c voi d mai n( St r i ng[ ] ar gs ) {
Si mpl eThr ead par al l el = new Si mpl eThr ead( ) ;
Syst em. out . pr i nt l n( " Cr eat e t he t hr ead" ) ;
par al l el . st ar t ( ) ;
Syst em. out . pr i nt l n( " St ar t ed t he t hr ead" ) ;
Syst em. out . pr i nt l n( " End" ) ;
}
}
Output
Cr eat e t he t hr ead
St ar t ed t he t hr ead
End
Message 0 Fr om: A
Message 1 Fr om: A
Message 2 Fr om: A

UIU Lecture 6b, CSI 211
4/6
Message 3 Fr om: A

ii) Implementing the Runnable interface

First, have your class implement the Runnable interface, which has one method,
run(). This run() plays the same role as the run() in the Thread subclass in the first
method.
Second, create an instance of the Thread class, passing an instance of your class to
the constructor. Finally, send the thread object the start() method.

cl ass SecondMet hod i mpl ement s Runnabl e {
publ i c voi d r un( ) {
f or ( i nt count = 0; count < 4; count ++)
Syst em. out . pr i nt l n( " Message " + count + " Fr om: B" ) ;
}
}
cl ass Test Thr ead {
publ i c st at i c voi d mai n( St r i ng[ ] ar gs ) {
SecondMet hod not AThr ead = new SecondMet hod( ) ;
Thr ead par al l el = new Thr ead( not AThr ead ) ;
Syst em. out . pr i nt l n( " Cr eat e t he t hr ead" ) ;
par al l el . st ar t ( ) ;
Syst em. out . pr i nt l n( " St ar t ed t he t hr ead" ) ;
Syst em. out . pr i nt l n( " End" ) ;
}
}
Output
Cr eat e t he t hr ead
St ar t ed t he t hr ead
End
Message 0 Fr om: B
Message 1 Fr om: B
Message 2 Fr om: B
Message 3 Fr om: B



UIU Lecture 6b, CSI 211
5/6

Giving a Thread a Name

We can give each thread a string id, which can be useful.

cl ass SecondMet hod i mpl ement s Runnabl e {
publ i c voi d r un( ) {
f or ( i nt count = 0; count < 2; count ++)
Syst em. out . pr i nt l n( " Message " + count + " Fr om: " +
Thr ead. cur r ent Thr ead( ) . get Name( ) ) ;
}
}
cl ass Test Thr ead {
publ i c st at i c voi d mai n( St r i ng[ ] ar gs ) {
Thr ead a = new Thr ead( new SecondMet hod( ) , " Mom" ) ;
Thr ead b = new Thr ead( new SecondMet hod( ) , " Dad" ) ;
Syst em. out . pr i nt l n( " Cr eat e t he t hr ead" ) ;
a. st ar t ( ) ;
b. st ar t ( ) ;
Syst em. out . pr i nt l n( " End" ) ;
}
}
Output
Cr eat e t he t hr ead
End
Message 0 Fr om: Mom
Message 1 Fr om: Mom
Message 0 Fr om: Dad
Message 1 Fr om: Dad



Parallelism
In this example we show some actual parallelism. Note that the output from the different
threads is mixed.

publ i c cl ass Si mpl eThr ead ext ends Thr ead
{
pr i vat e i nt maxCount = 32;
publ i c Si mpl eThr ead( St r i ng name )
{
super ( name ) ;
}
publ i c Si mpl eThr ead( St r i ng name, i nt r epet i t i ons )
{
super ( name ) ;
maxCount = r epet i t i ons;
}
publ i c Si mpl eThr ead( i nt r epet i t i ons )
{
maxCount = r epet i t i ons;
}
publ i c voi d r un( )
{

UIU Lecture 6b, CSI 211
6/6
f or ( i nt count = 0; count < maxCount ; count ++)
{
Syst em. out . pr i nt l n( count + " Fr om: " + get Name( ) ) ;
}
}
}

cl ass Test Thr ead
{
publ i c st at i c voi d mai n( St r i ng[ ] ar gs )
{
Si mpl eThr ead f i r st = new Si mpl eThr ead( 5 ) ;
Si mpl eThr ead second = new Si mpl eThr ead( 5 ) ;
f i r st . st ar t ( ) ;
second. st ar t ( ) ;
Syst em. out . pr i nt l n( " End" ) ;
}
}
Output
End
0 Fr om: Thr ead- 0
1 Fr om: Thr ead- 0
2 Fr om: Thr ead- 0
0 Fr om: Thr ead- 1
1 Fr om: Thr ead- 1
2 Fr om: Thr ead- 1
3 Fr om: Thr ead- 0
3 Fr om: Thr ead- 1
4 Fr om: Thr ead- 0
4 Fr om: Thr ead- 1







*************** End of Lecture 7a **************

UIU Lecture 7, CSI 211
1/7
United International University

Trimester: Spring 2011
Course: CSI 211
Course Title: Object Oriented Programming
Lecture 7: Generics



Generic Programming
Generic programming is a sub-discipline of computer science that deals with finding
abstract representations of efficient algorithms, data structures, and other software
concepts.
J DK 1.5 introduces several extensions to the J ava programming language. One of these is
the introduction of generics. You may be familiar with similar constructs from other
languages, most notably C++templates.
Motivation to avoid overloading methods for a class.
publ i c cl ass Over l oadedMet hods{

public static void printArray( Integer[] inputArray{
f or ( I nt eger el ement : i nput Ar r ay )
Syst em. out . pr i nt f ( " %s " , el ement ) ;

Syst em. out . pr i nt l n( ) ;

}

public static void printArray( Double[] inputArray )
{
f or ( Doubl e el ement : i nput Ar r ay )
Syst em. out . pr i nt f ( " %s " , el ement ) ;
Syst em. out . pr i nt l n( ) ;
}

publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
I nt eger [ ] i nt eger Ar r ay = { 1, 2, 3, 4, 5, 6 };
Doubl e[ ] doubl eAr r ay = { 1. 1, 2. 2, 3. 3};
pr i nt Ar r ay( i nt eger Ar r ay ) ;
pr i nt Ar r ay( doubl eAr r ay ) ;
}
}


UIU Lecture 7, CSI 211
2/7
Using a generic method to avoid the overloading-
publ i c cl ass Gener i cMet hods{

public static < E > void printArray( E[] inputArray ){
f or ( E el ement : i nput Ar r ay )
Syst em. out . pr i nt f ( " %s " , el ement ) ;
Syst em. out . pr i nt l n( ) ;

}


publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
I nt eger [ ] i nt eger Ar r ay = { 1, 2, 3, 4, 5, 6 };
Doubl e[ ] doubl eAr r ay = { 1. 1, 2. 2, 3. 3};

pr i nt Ar r ay( i nt eger Ar r ay ) ;
pr i nt Ar r ay( doubl eAr r ay ) ;
}
}

Generic Classes
Let's begin by designing a non-generic Box class that operates on objects of any type.
It need only provide two methods: add, which adds an object to the box, and get ,
which retrieves it:
publ i c cl ass Box {

pr i vat e Obj ect obj ect ;

publ i c voi d add( Obj ect obj ect ) {
t hi s. obj ect = obj ect ;
}

publ i c Obj ect get ( ) {
r et ur n obj ect ;
}
}


Since its methods accept or return Object, you're free to pass in whatever you want,
provided that it's not one of the primitive types. However, should you need to restrict
the contained type to something specific (like Integer), your only option would be to
specify the requirement in documentation (or in this case, a comment), which of
course the compiler knows nothing about:




UIU Lecture 7, CSI 211
3/7
publ i c cl ass BoxDemo1 {

publ i c st at i c voi d mai n( St r i ng[ ] ar gs) {

/ / ONLY pl ace I nt eger obj ect s i nt o t hi s box!
Box i nt eger Box = new Box( ) ;

i nt eger Box. add( new I nt eger ( 10) ) ;
I nt eger someI nt eger = ( I nt eger ) i nt eger Box. get ( ) ;
Syst em. out . pr i nt l n( someI nt eger ) ;
}
}


The BoxDemo1 program creates an I nt eger object, passes it to add, then assigns that
same object to someI nt eger by the return value of get . It then prints the object's
value (10) to standard output. We know that the cast from Obj ect to I nt eger is
correct. But remember, the compiler knows nothing about this it just trusts that our
cast is correct. Furthermore, it will do nothing to prevent a careless programmer from
passing in an object of the wrong type, such as St r i ng:

publ i c cl ass BoxDemo2 {

publ i c st at i c voi d mai n( St r i ng[ ] ar gs) {

/ / ONLY pl ace I nt eger obj ect s i nt o t hi s box!
Box i nt eger Box = new Box( ) ;

/ / I magi ne t hi s i s one par t of a l ar ge appl i cat i on
/ / modi f i ed by one pr ogr ammer .
i nt eger Box. add( " 10" ) ; / / not e how t he t ype i s now
St r i ng

/ / . . . and t hi s i s anot her , per haps wr i t t en
/ / by a di f f er ent pr ogr ammer
I nt eger someI nt eger = ( I nt eger ) i nt eger Box. get ( ) ;
Syst em. out . pr i nt l n( someI nt eger ) ;
}
}

In BoxDemo2 we've stored the number 10 as a St r i ng, which could be the case when,
say, a GUI collects input from the user. However, the existing cast from Obj ect to
I nt eger has mistakenly been overlooked. This is clearly a bug, but because the code
still compiles, you wouldn't know anything is wrong until runtime, when the
application crashes with a

Cl assCast Except i on:
Except i on i n t hr ead " mai n"
j ava. l ang. Cl assCast Except i on:
j ava. l ang. St r i ng cannot be cast t o j ava. l ang. I nt eger
at BoxDemo2. mai n( BoxDemo2. j ava: 6)

UIU Lecture 7, CSI 211
4/7
If the Box class had been designed with generics in mind, this mistake would have been
caught by the compiler, instead of crashing the application at runtime.
Let's update our Box class to use generics.

/ **
* Gener i c ver si on of t he Box cl ass.
*/
publ i c cl ass Box<T> {

pr i vat e T t; / / T st ands f or " Type"

publ i c voi d add( T t) {
t hi s. t = t;
}

publ i c T get ( ) {
r et ur n t;
}
}
To reference this generic class from within your own code, you must perform a
generic type invocation, which replaces T with some concrete value, such as I nt eger :
Box<I nt eger > i nt eger Box;
You can think of a generic type invocation as being similar to an ordinary method
invocation, but instead of passing an argument to a method, you're passing a type
argument I nt eger in this case to the Box class itself.
i nt eger Box = new Box<I nt eger >( ) ;
Or, you can put the entire statement on one line, such as:
Box<I nt eger > i nt eger Box = new Box<I nt eger >( ) ;
Finally BoxDemo with usage of generic is as follows:
publ i c cl ass BoxDemo3 {

publ i c st at i c voi d mai n( St r i ng[ ] ar gs) {
Box<I nt eger > i nt eger Box = new Box<I nt eger >( ) ;
i nt eger Box. add( new I nt eger ( 10) ) ;
I nt eger someI nt eger = i nt eger Box. get ( ) ; / / no cast !
Syst em. out . pr i nt l n( someI nt eger ) ;
}
}


UIU Lecture 7, CSI 211
5/7
Type Parameter Conventions
The most commonly used type parameter names are:
E
Element (used extensively by the J ava Collections Framework)
K
Key
N
Number
T
Type
V
Value

S, U, V, etc. 2nd, 3rd, 4th types

Generic Methods with Type Parameters
Type parameters can also be declared within method and constructor signatures to
create generic methods and generic constructors. This is similar to declaring a
generic type, but the type parameter's scope is limited to the method or constructor in
which it's declared.

/ **
* Thi s ver si on i nt r oduces a gener i c met hod.
*/
publ i c cl ass Box<T> {

pr i vat e T t ;

publ i c voi d add( T t ) {
t hi s. t = t ;
}

publ i c T get ( ) {
r et ur n t ;
}

public <U> void inspect(U u){
System.out.println("T: " + t.getClass().getName());
System.out.println("U: " + u.getClass().getName());
}

publ i c st at i c voi d mai n( St r i ng[ ] ar gs) {
Box<I nt eger > i nt eger Box = new Box<I nt eger >( ) ;
i nt eger Box. add( new I nt eger ( 10) ) ;
i nt eger Box. i nspect ( " some t ext " ) ;
}

UIU Lecture 7, CSI 211
6/7
}

Here we've added one generic method, named i nspect , that defines one type
parameter, named U. This method accepts an object and prints its type to standard
output. For comparison, it also prints out the type of T. For convenience, this class
now also has a mai n method so that it can be run as an application. The output from
this program is:

T: j ava. l ang. I nt eger
U: j ava. l ang. St r i ng


Bounded Type Parameters
There may be times when you'll want to restrict the kinds of types that are allowed to
be passed to a type parameter. For example, a method that operates on numbers might
only want to accept instances of Number or its subclasses. This is what bounded type
parameters are for.
To declare a bounded type parameter, list the type parameter's name, followed by the
ext ends keyword, followed by its upper bound, which in this example is Number .
Note that, in this context, ext ends is used in a general sense to mean either "extends"
(as in classes) or "implements" (as in interfaces):

/ **
* Thi s ver si on i nt r oduces a bounded t ype par amet er .
*/
publ i c cl ass Box<T> {

pr i vat e T t ;

publ i c voi d add( T t ) {
t hi s. t = t ;
}

publ i c T get ( ) {
r et ur n t ;
}

publ i c <U ext ends Number > voi d i nspect ( U u) {
Syst em. out . pr i nt l n( " T: " + t . get Cl ass( ) . get Name( ) ) ;
Syst em. out . pr i nt l n( " U: " + u. get Cl ass( ) . get Name( ) ) ;
}

publ i c st at i c voi d mai n( St r i ng[ ] ar gs) {
Box<I nt eger > i nt eger Box = new Box<I nt eger >( ) ;
i nt eger Box. add( new I nt eger ( 10) ) ;
i nt eger Box. i nspect ( " some t ext " ) ; / / er r or : t hi s i s
/ / st i l l St r i ng!
}
}

UIU Lecture 7, CSI 211
7/7

By modifying our generic method to include this bounded type parameter,
compilation will now fail, since our invocation of i nspect still includes a
St r i ng:
Box. j ava: 21: <U>i nspect ( U) i n Box<j ava. l ang. I nt eger > cannot
be appl i ed t o ( j ava. l ang. St r i ng)
i nt eger Box. i nspect ( " 10" ) ;
^
1 er r or





*************** End of Lecture 7 **************

UIU Lecture 7, CSI 211
1/7
United International University

Trimester: Spring 2011
Course: CSI 211
Course Title: Object Oriented Programming
Lecture 7: Generics



Generic Programming
Generic programming is a sub-discipline of computer science that deals with finding
abstract representations of efficient algorithms, data structures, and other software
concepts.
J DK 1.5 introduces several extensions to the J ava programming language. One of these is
the introduction of generics. You may be familiar with similar constructs from other
languages, most notably C++templates.
Motivation to avoid overloading methods for a class.
publ i c cl ass Over l oadedMet hods{

public static void printArray( Integer[] inputArray{
f or ( I nt eger el ement : i nput Ar r ay )
Syst em. out . pr i nt f ( " %s " , el ement ) ;

Syst em. out . pr i nt l n( ) ;

}

public static void printArray( Double[] inputArray )
{
f or ( Doubl e el ement : i nput Ar r ay )
Syst em. out . pr i nt f ( " %s " , el ement ) ;
Syst em. out . pr i nt l n( ) ;
}

publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
I nt eger [ ] i nt eger Ar r ay = { 1, 2, 3, 4, 5, 6 };
Doubl e[ ] doubl eAr r ay = { 1. 1, 2. 2, 3. 3};
pr i nt Ar r ay( i nt eger Ar r ay ) ;
pr i nt Ar r ay( doubl eAr r ay ) ;
}
}


UIU Lecture 7, CSI 211
2/7
Using a generic method to avoid the overloading-
publ i c cl ass Gener i cMet hods{

public static < E > void printArray( E[] inputArray ){
f or ( E el ement : i nput Ar r ay )
Syst em. out . pr i nt f ( " %s " , el ement ) ;
Syst em. out . pr i nt l n( ) ;

}


publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
I nt eger [ ] i nt eger Ar r ay = { 1, 2, 3, 4, 5, 6 };
Doubl e[ ] doubl eAr r ay = { 1. 1, 2. 2, 3. 3};

pr i nt Ar r ay( i nt eger Ar r ay ) ;
pr i nt Ar r ay( doubl eAr r ay ) ;
}
}

Generic Classes
Let's begin by designing a non-generic Box class that operates on objects of any type.
It need only provide two methods: add, which adds an object to the box, and get ,
which retrieves it:
publ i c cl ass Box {

pr i vat e Obj ect obj ect ;

publ i c voi d add( Obj ect obj ect ) {
t hi s. obj ect = obj ect ;
}

publ i c Obj ect get ( ) {
r et ur n obj ect ;
}
}


Since its methods accept or return Object, you're free to pass in whatever you want,
provided that it's not one of the primitive types. However, should you need to restrict
the contained type to something specific (like Integer), your only option would be to
specify the requirement in documentation (or in this case, a comment), which of
course the compiler knows nothing about:




UIU Lecture 7, CSI 211
3/7
publ i c cl ass BoxDemo1 {

publ i c st at i c voi d mai n( St r i ng[ ] ar gs) {

/ / ONLY pl ace I nt eger obj ect s i nt o t hi s box!
Box i nt eger Box = new Box( ) ;

i nt eger Box. add( new I nt eger ( 10) ) ;
I nt eger someI nt eger = ( I nt eger ) i nt eger Box. get ( ) ;
Syst em. out . pr i nt l n( someI nt eger ) ;
}
}


The BoxDemo1 program creates an I nt eger object, passes it to add, then assigns that
same object to someI nt eger by the return value of get . It then prints the object's
value (10) to standard output. We know that the cast from Obj ect to I nt eger is
correct. But remember, the compiler knows nothing about this it just trusts that our
cast is correct. Furthermore, it will do nothing to prevent a careless programmer from
passing in an object of the wrong type, such as St r i ng:

publ i c cl ass BoxDemo2 {

publ i c st at i c voi d mai n( St r i ng[ ] ar gs) {

/ / ONLY pl ace I nt eger obj ect s i nt o t hi s box!
Box i nt eger Box = new Box( ) ;

/ / I magi ne t hi s i s one par t of a l ar ge appl i cat i on
/ / modi f i ed by one pr ogr ammer .
i nt eger Box. add( " 10" ) ; / / not e how t he t ype i s now
St r i ng

/ / . . . and t hi s i s anot her , per haps wr i t t en
/ / by a di f f er ent pr ogr ammer
I nt eger someI nt eger = ( I nt eger ) i nt eger Box. get ( ) ;
Syst em. out . pr i nt l n( someI nt eger ) ;
}
}

In BoxDemo2 we've stored the number 10 as a St r i ng, which could be the case when,
say, a GUI collects input from the user. However, the existing cast from Obj ect to
I nt eger has mistakenly been overlooked. This is clearly a bug, but because the code
still compiles, you wouldn't know anything is wrong until runtime, when the
application crashes with a

Cl assCast Except i on:
Except i on i n t hr ead " mai n"
j ava. l ang. Cl assCast Except i on:
j ava. l ang. St r i ng cannot be cast t o j ava. l ang. I nt eger
at BoxDemo2. mai n( BoxDemo2. j ava: 6)

UIU Lecture 7, CSI 211
4/7
If the Box class had been designed with generics in mind, this mistake would have been
caught by the compiler, instead of crashing the application at runtime.
Let's update our Box class to use generics.

/ **
* Gener i c ver si on of t he Box cl ass.
*/
publ i c cl ass Box<T> {

pr i vat e T t; / / T st ands f or " Type"

publ i c voi d add( T t) {
t hi s. t = t;
}

publ i c T get ( ) {
r et ur n t;
}
}
To reference this generic class from within your own code, you must perform a
generic type invocation, which replaces T with some concrete value, such as I nt eger :
Box<I nt eger > i nt eger Box;
You can think of a generic type invocation as being similar to an ordinary method
invocation, but instead of passing an argument to a method, you're passing a type
argument I nt eger in this case to the Box class itself.
i nt eger Box = new Box<I nt eger >( ) ;
Or, you can put the entire statement on one line, such as:
Box<I nt eger > i nt eger Box = new Box<I nt eger >( ) ;
Finally BoxDemo with usage of generic is as follows:
publ i c cl ass BoxDemo3 {

publ i c st at i c voi d mai n( St r i ng[ ] ar gs) {
Box<I nt eger > i nt eger Box = new Box<I nt eger >( ) ;
i nt eger Box. add( new I nt eger ( 10) ) ;
I nt eger someI nt eger = i nt eger Box. get ( ) ; / / no cast !
Syst em. out . pr i nt l n( someI nt eger ) ;
}
}


UIU Lecture 7, CSI 211
5/7
Type Parameter Conventions
The most commonly used type parameter names are:
E
Element (used extensively by the J ava Collections Framework)
K
Key
N
Number
T
Type
V
Value

S, U, V, etc. 2nd, 3rd, 4th types

Generic Methods with Type Parameters
Type parameters can also be declared within method and constructor signatures to
create generic methods and generic constructors. This is similar to declaring a
generic type, but the type parameter's scope is limited to the method or constructor in
which it's declared.

/ **
* Thi s ver si on i nt r oduces a gener i c met hod.
*/
publ i c cl ass Box<T> {

pr i vat e T t ;

publ i c voi d add( T t ) {
t hi s. t = t ;
}

publ i c T get ( ) {
r et ur n t ;
}

public <U> void inspect(U u){
System.out.println("T: " + t.getClass().getName());
System.out.println("U: " + u.getClass().getName());
}

publ i c st at i c voi d mai n( St r i ng[ ] ar gs) {
Box<I nt eger > i nt eger Box = new Box<I nt eger >( ) ;
i nt eger Box. add( new I nt eger ( 10) ) ;
i nt eger Box. i nspect ( " some t ext " ) ;
}

UIU Lecture 7, CSI 211
6/7
}

Here we've added one generic method, named i nspect , that defines one type
parameter, named U. This method accepts an object and prints its type to standard
output. For comparison, it also prints out the type of T. For convenience, this class
now also has a mai n method so that it can be run as an application. The output from
this program is:

T: j ava. l ang. I nt eger
U: j ava. l ang. St r i ng


Bounded Type Parameters
There may be times when you'll want to restrict the kinds of types that are allowed to
be passed to a type parameter. For example, a method that operates on numbers might
only want to accept instances of Number or its subclasses. This is what bounded type
parameters are for.
To declare a bounded type parameter, list the type parameter's name, followed by the
ext ends keyword, followed by its upper bound, which in this example is Number .
Note that, in this context, ext ends is used in a general sense to mean either "extends"
(as in classes) or "implements" (as in interfaces):

/ **
* Thi s ver si on i nt r oduces a bounded t ype par amet er .
*/
publ i c cl ass Box<T> {

pr i vat e T t ;

publ i c voi d add( T t ) {
t hi s. t = t ;
}

publ i c T get ( ) {
r et ur n t ;
}

publ i c <U ext ends Number > voi d i nspect ( U u) {
Syst em. out . pr i nt l n( " T: " + t . get Cl ass( ) . get Name( ) ) ;
Syst em. out . pr i nt l n( " U: " + u. get Cl ass( ) . get Name( ) ) ;
}

publ i c st at i c voi d mai n( St r i ng[ ] ar gs) {
Box<I nt eger > i nt eger Box = new Box<I nt eger >( ) ;
i nt eger Box. add( new I nt eger ( 10) ) ;
i nt eger Box. i nspect ( " some t ext " ) ; / / er r or : t hi s i s
/ / st i l l St r i ng!
}
}

UIU Lecture 7, CSI 211
7/7

By modifying our generic method to include this bounded type parameter,
compilation will now fail, since our invocation of i nspect still includes a
St r i ng:
Box. j ava: 21: <U>i nspect ( U) i n Box<j ava. l ang. I nt eger > cannot
be appl i ed t o ( j ava. l ang. St r i ng)
i nt eger Box. i nspect ( " 10" ) ;
^
1 er r or





*************** End of Lecture 7 **************

UIU Lecture 8b, CSI 211
1/6
United International University

Course: CSI 211
Course Title: Object Oriented Programming
Lecture 8b: Serialization


Serialization
Serialization allows objects to be converted to a sequence of bytes and The
sequence of bytes can be stored in a file, database, sent to a remote machine etc.
The sequence of bytes can be used to recreate the original object using
deserialization.


Serializable

Only an object that implements the Serializable interface can be saved and
restored by the serialization facilities. The Serializable interface defines no
members.
It is simply used to indicate that a class may be serialized. If a class is serializable,
all of its subclasses are also serializable.
Variables that are declared as transient are not saved by the serialization facilities.
Also, static variables are not saved.


Making an Object Serializable
To serialize an object, the object class must implement the interface
java.io.Serializable. Serializable has no methods

Example

i mpor t j ava. i o. Ser i al i zabl e;
cl ass Roger i mpl ement s Ser i al i zabl e
{
publ i c i nt l owBi d;

publ i c Roger ( i nt l owBi d )
{
t hi s. l owBi d = l owBi d;
}


UIU Lecture 8b, CSI 211
2/6
publ i c St r i ng t oSt r i ng( )
{
r et ur n " " + l owBi d;
}
}

Serializing and Deserializing Objects

The writeObject method of ObjectOutputStream serializes objects
The readObject method of ObjectInputStream deserializes objects

Example
i mpor t j ava. i o. *;

cl ass Ser i al i zeDeser i al i ze {
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) t hr ows I OExcept i on {
ser i al i ze( ) ;
deser i al i ze( ) ;
}

publ i c st at i c voi d ser i al i ze( ) t hr ows Except i on {
Out put St r eamout put Fi l e =
new Fi l eOut put St r eam( " Ser i al i zed" ) ;
Obj ect Out put St r eamcout =
new Obj ect Out put St r eam( out put Fi l e ) ;
cout . wr i t eObj ect ( new Roger ( 1) ) ;
cout . cl ose( ) ;
}

publ i c st at i c voi d deser i al i ze( ) t hr ows Except i on {
I nput St r eami nput Fi l e =
new Fi l eI nput St r eam( " Ser i al i zed" ) ;
Obj ect I nput St r eamci n =
new Obj ect I nput St r eam( i nput Fi l e ) ;
Syst em. out . pr i nt l n( ci n. r eadObj ect ( ) ) ;
}
}
Output
1


Saving and Recovering - A Simple Example

publ i c cl ass St udent i mpl ement s Ser i al i zabl e
{
St r i ng name;
St r i ng addr ess;

publ i c St udent ( St r i ng name, St r i ng addr ess )
{

UIU Lecture 8b, CSI 211
3/6
t hi s. name = name;
t hi s. addr ess = addr ess;
}

publ i c St r i ng t oSt r i ng( )
{
r et ur n name + " @" + addr ess + " \ n" ;
}
}


publ i c cl ass St udent Li st i mpl ement s Ser i al i zabl e
{
Vect or l i st = new Vect or ( ) ;
St r i ng st or ageFi l eName;

publ i c St udent Li st ( St r i ng f i l eFor St or age)
{
st or ageFi l eName = f i l eFor St or age;
}

publ i c voi d addSt udent ( St udent addToLi st )
{
l i st . addEl ement ( addToLi st ) ;
}

publ i c St r i ng t oSt r i ng( )
{
r et ur n l i st . t oSt r i ng( ) ;
}

/ / Have t he l i st save i t sel f i n a f i l e
publ i c voi d save( ) t hr ows I OExcept i on
{
Out put St r eamout put Fi l e =
new Fi l eOut put St r eam( st or ageFi l eName ) ;
Obj ect Out put St r eamcout =
new Obj ect Out put St r eam( out put Fi l e ) ;
cout . wr i t eObj ect ( t hi s ) ;
cout . cl ose( ) ;
}




/ / Recover a St udent Li st f r oma f i l e
publ i c st at i c St udent Li st f r omFi l e( St r i ng st udent Li st Fi l e)
t hr ows
Opt i onal Dat aExcept i on,
Cl assNot FoundExcept i on,
I OExcept i on
{
I nput St r eami nput Fi l e =
new Fi l eI nput St r eam( st udent Li st Fi l e ) ;
Obj ect I nput St r eamci n =
new Obj ect I nput St r eam( i nput Fi l e ) ;

UIU Lecture 8b, CSI 211
4/6
St udent Li st r ecover edLi st =
( St udent Li st ) ci n. r eadObj ect ( ) ;
ci n. cl ose( ) ;
r et ur n r ecover edLi st ;
}
}

The driver program and Sample output
cl ass Test
publ i c st at i c voi d mai n( St r i ng ar gs) t hr ows Except i on
{
St udent Li st cs535 = new St udent Li st ( " cs535Fi l e" ) ;
cs535. addSt udent (
new St udent ( " Roger " , " whi t ney@r ohan" ) ) ;
cs535. addSt udent (
new St udent ( " Sam" , " masc1232@r ohan" ) ) ;
cs535. addSt udent (
new St udent ( " Ngu" , " masc1111@r ohan" ) ) ;
cs535. addSt udent (
new St udent ( " cat Man" , " masc43221@r ohan" ) ) ;
Syst em. out . pr i nt l n( cs535) ;
cs535. save( ) ;

St udent Li st r ecover edCl ass =
St udent Li st . f r omFi l e( " cs535Fi l e" ) ;
Syst em. out . pr i nt l n( r ecover edCl ass) ;
}
}

Output
[Roger@whitney@rohan
, Sam@masc1232@rohan
, Ngu@masc1111@rohan
, catMan@masc43221@rohan
]
[Roger@whitney@rohan
, Sam@masc1232@rohan
, Ngu@masc1111@rohan
, catMan@masc43221@rohan
]

UIU Lecture 8b, CSI 211
5/6

Non-Serializable Objects

Some objects should not be serialized
objects that hold system resources
Some values or objects can be recomputed or are not important to serialize



If an object has a field that should not be serialized declare the field transient
That field will not be included in the serialization of the object


cl ass Roger i mpl ement s Ser i al i zabl e
{
pr i vat e i nt l owBi d;
pr i vat e t r ansi ent f l oat aver ageBi d;
pr i vat e i nt hi ghBi d;

publ i c Roger ( i nt l owBi d, i nt hi ghBi d )
{
t hi s. l owBi d = l owBi d;
t hi s. hi ghBi d = hi ghBi d;
aver ageBi d = ( l owBi d + hi ghBi d) / 2;
}

publ i c St r i ng t oSt r i ng( )
{
r et ur n " " + l owBi d + " " + aver ageBi d;
}
}

cl ass Tr ansi ent Exampl e
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) t hr ows Except i on
{
ser i al i ze( ) ;
deser i al i ze( ) ;
}

publ i c st at i c voi d ser i al i ze( ) t hr ows I OExcept i on
{
Out put St r eamout put Fi l e =
new Fi l eOut put St r eam( " Ser i al i zed" ) ;
Obj ect Out put St r eamcout =
new Obj ect Out put St r eam( out put Fi l e ) ;
cout . wr i t eObj ect ( new Roger ( 1, 5 ) ) ;
cout . cl ose( ) ;
}
publ i c st at i c voi d deser i al i ze( ) t hr ows Except i on
{

UIU Lecture 8b, CSI 211
6/6
I nput St r eami nput Fi l e =
new Fi l eI nput St r eam( " Ser i al i zed" ) ;
Obj ect I nput St r eamci n =
new Obj ect I nput St r eam( i nput Fi l e ) ;
Syst em. out . pr i nt l n( ci n. r eadObj ect ( ) ) ;
}
}

Output
1 0.0






*************** End of Lecture 8b **************


UIU Lecture 9a, CSI 211
1/3
United International University

Course: CSI 211
Course Title: Object Oriented Programming
Lecture 9a: Internationalization

Internationalization
Are dates formatted as:
10/13/97
13/10/97
13.10.97

Are numbers formatted as:
1,234.56
1.234,56
1;234.56


An instances of the java.util.Locale class contains the rules for a language in a
location
Each J ava virtual machine has a default instance of the Locale class, which should
be for the local language rules in the current country


Using the Default Locale to Format
i mpor t j ava. t ext . *;
cl ass For mat Usi ngLocal Rul es
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) t hr ows Except i on
{
Number For mat number = Number For mat . get I nst ance( ) ;
Number For mat cur r ency =
Number For mat . get Cur r encyI nst ance( ) ;
Dat eFor mat shor t Dat e =
Dat eFor mat . get Dat eI nst ance( Dat eFor mat . SHORT) ;
Dat eFor mat f ul l Ti me =
Dat eFor mat . get Ti meI nst ance( Dat eFor mat . FULL ) ;

Syst em. out . pr i nt l n( " Number : " + number . f or mat ( 123456 ) ) ;
Syst em. out . pr i nt l n( " Cur r ency: " +
cur r ency. f or mat ( 1234. 56 ) ) ;
Syst em. out . pr i nt l n( " Shor t Dat e: " +
shor t Dat e. f or mat ( new Dat e( ) ) ) ;
Syst em. out . pr i nt l n( " Ful l Ti me: " +
f ul l Ti me. f or mat ( new Dat e( ) ) ) ;
}
}


UIU Lecture 9a, CSI 211
2/3
Output
Number: 123,456
Currency: $1,234.56
ShortDate: 10/13/97
FullTime: 5:15:42 oclock PM PDT


Example

class FormatExplicitlyCallingDifferentLocale
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
Syst em. out . pr i nt l n( " - - - - - - - US Engl i sh- - - - - - " ) ;
i nt er nat i onal Pr i nt ( Local e. get Def aul t ( ) ) ;
Syst em. out . pr i nt l n( " - - - - - - - Spani sh Spani sh- - - - - - " ) ;
i nt er nat i onal Pr i nt ( new Local e( " es" , " ES" ) ) ;
}

publ i c st at i c voi d i nt er nat i onal Pr i nt ( Local e cust om)
{
Number For mat number =
Number For mat . get I nst ance( cust om) ;
Number For mat cur r ency =
Number For mat . get Cur r encyI nst ance( cust om) ;
Dat eFor mat shor t Dat e = Dat eFor mat . get Dat eI nst ance(
Dat eFor mat . SHORT, cust om) ;
Dat eFor mat f ul l Dat e = Dat eFor mat . get Dat eI nst ance(
Dat eFor mat . FULL, cust om) ;
Dat eFor mat shor t Ti me = Dat eFor mat . get Ti meI nst ance(
Dat eFor mat . SHORT, cust om) ;
Dat eFor mat l ongTi me = Dat eFor mat . get Ti meI nst ance(
Dat eFor mat . LONG, cust om) ;
Syst em. out . pr i nt l n( " Number : " +
number . f or mat ( 123456 ) ) ;
Syst em. out . pr i nt l n( " Cur r ency: " +
cur r ency. f or mat ( 1234. 56 ) ) ;
Syst em. out . pr i nt l n( " Shor t Dat e: " +
shor t Dat e. f or mat ( new Dat e( ) ) ) ;
Syst em. out . pr i nt l n( " Ful l Dat e: " +
f ul l Dat e. f or mat ( new Dat e( ) ) ) ;
Syst em. out . pr i nt l n( " Shor t Ti me: " +
shor t Ti me. f or mat ( new Dat e( ) ) ) ;
Syst em. out . pr i nt l n( " LongTi me: " +
l ongTi me. f or mat ( new Dat e( ) ) ) ;
}
}

Output
-------US English------
Number: 123,456
Currency: $1,234.56
ShortDate: 10/12/97


UIU Lecture 9a, CSI 211
3/3
FullDate: Sunday, October 12, 1997
ShortTime: 9:45 PM
LongTime: 9:45:46 PM PDT

-------Spanish Spanish------
Number: 123.456
Currency: 1.234,56 Pts
ShortDate: 13/10/97
FullDate: lunes 13 de octubre de 1997
ShortTime: 6:45
LongTime: 6:45:46 GMT+02:00


Example - Hello World Tested

cl ass Thr eeHel l os
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
f or ei gnTest ( ) ;
Local e. set Def aul t ( new Local e( " es" , " ES" ) ) ;
f or ei gnTest ( ) ;
Local e. set Def aul t ( new Local e( " de" , " DE" ) ) ;
f or ei gnTest ( ) ;
}

publ i c st at i c voi d f or ei gnTest ( )
{
Resour ceBundl e gr eet i ngs =
Resour ceBundl e. get Bundl e( " Gr eet i ngs" ) ;

Syst em. out . pr i nt l n( " - - - - " +
gr eet i ngs. get St r i ng( " l anguage" ) +
" - - - - " ) ;
Syst em. out . pr i nt l n( gr eet i ngs. get St r i ng( " hel l o" ) ) ;
}
}

Output
----English----
Hello World!
----Espaol----
Hola mundo!
----Deutsch----
Hallo, Welt!


*************** End of Lecture 9a **************

UIU Lecture 9b, CSI 211
1/7
United International University

Course: CSI 211
Course Title: Object Oriented Programming
Lecture 9b: Java Foundation Classes

Java Foundation Classes (JFC)
J ava Foundat i on Cl asses ( J FC) ar e pr e- wr i t t en code i n t he f or mof
cl ass l i br ar i es ( coded r out i nes) t hat gi ve t he pr ogr ammer a
compr ehensi ve set of gr aphi cal user i nt er f ace ( GUI ) r out i nes t o
use.

J FC Contains:
Abstract Window Toolkit (AWT)
Swing Components
Lightweight components providing wide range of options
J ava 2D
Full range of 2D operations
Accessibility Framework



Types of things in AWT

Components
Basic UI things like

Buttons, Checkboxes, Choices,
Lists, Menus, and Text Fields
Scrollbars and Labels

Containers
Contain components and containers
The AWT provides three types of containers,

UIU Lecture 9b, CSI 211
2/7
o The Window subclasses -- Dialog, FileDialog, and Frame -- provide
windows to contain components.
o A Panel groups components within an area of an existing window.
o A ScrollPane is similar to a panel, but its purpose is more specialized: to
display a potentially large component in a limited amount of space,
generally using scrollbars to control which part of the component is
displayed


LayoutManagers
Position items in window
For example, a window is a container that contains components
such as buttons and labels. The layout manager in effect for the
window determines how the components are sized and positioned
inside the window.
Examples:
java.awt.BorderLayout
java.awt.FlowLayout j
java.awt.GridLayout
java.awt.GridBagLayout

Graphics
Drawing on the screen

publ i c cl ass Cl ear 1 ext ends Appl et {

publ i c voi d pai nt ( Gr aphi cs g) {
g. f i l l Oval ( 20, 20, 180, 180) ;
g. cl ear Rect ( 50, 70, 120, 80) ;
}

}


UIU Lecture 9b, CSI 211
3/7

Applets and Applications

GUI components used by
applications
applets

1. Applications

This example shows a simple application. Subclass Frame to get a window. The paint()
method is called when window needs to be drawn. Do not call paint() directly. Becareful!
You need to kill the process to quit this program.
i mpor t j ava. awt . *;
cl ass Hel l oAppl i cat i on ext ends J Fr ame
{
publ i c voi d pai nt ( Gr aphi cs di spl ay )
{
i nt st ar t X = 30;
i nt st ar t Y = 40;
di spl ay. dr awSt r i ng( " Hel l o Wor l d" , st ar t X, st ar t Y ) ;
}
}
cl ass Test
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
Hel l oAppl i cat i on mai nWi ndow = new Hel l oAppl i cat i on( ) ;
i nt wi dt h = 150; / / i n pi xel s
i nt hei ght = 80;
i nt l ef t = 20;
i nt t op = 40;
mai nWi ndow. set Si ze( wi dt h, hei ght ) ;
mai nWi ndow. set Locat i on( l ef t , t op) ;
mai nWi ndow. set Ti t l e( " Hel l o" ) ;
mai nWi ndow. show( ) ;
}
}
Output




UIU Lecture 9b, CSI 211
4/7

This example uses a Text label instead of drawing text.
i mpor t j ava. awt . *;
cl ass Hel l oLabel ext ends Fr ame
{
publ i c Hel l oLabel ( i nt l ef t , i nt t op, i nt wi dt h, i nt hei ght , St r i ng
t i t l e )
{
super ( t i t l e ) ;
set Si ze( wi dt h, hei ght ) ;
set Locat i on( l ef t , t op) ;
Label hel l o = new Label ( " Hel l o Wor l d" , Label . CENTER) ;
add( hel l o, Bor der Layout . CENTER ) ;
show( ) ;
}
}
cl ass Test
{
publ i c st at i c voi d mai n( St r i ng ar gs[ ] )
{
Hel l oLabel mai nWi ndow = new Hel l oLabel ( 20, 40, 150, 80, " Hi
Dad" ) ;
}
}
Output



Listener


A listener is called when the user does something to the user interface that causes
an event.

Buttons support ActionListeners. When the mouse is pressed and released on a button, all
listeners are send the actionPerformed() method. In this example we only need to know
when the button was selected, so we do not use the ActionEvent.
i mpor t j ava. awt . *;
i mpor t j ava. awt . event . Act i onLi st ener ;
i mpor t j ava. awt . event . Act i onEvent ;
cl ass But t onExampl e ext ends Fr ame {
But t on r ed = new But t on( " Red" ) ;
But t on bl ue = new But t on( " Bl ue" ) ;

UIU Lecture 9b, CSI 211
5/7

publ i c But t onExampl e( i nt wi dt hI nPi xel s, i nt hei ght I nPi xel s ) {
set Ti t l e( " But t on Exampl e" ) ;
set Si ze( wi dt hI nPi xel s, hei ght I nPi xel s ) ;
set Layout ( new Fl owLayout ( ) ) ;
add( r ed ) ;
add( bl ue ) ;

r ed. addAct i onLi st ener ( new Col or Act i onLi st ener ( Col or . r ed) ) ;
bl ue. addAct i onLi st ener ( new Col or Act i onLi st ener ( Col or . bl ue) ) ;
show( ) ;
}
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) {
But t onExampl e wi ndow = new But t onExampl e( 200, 50) ;
}

cl ass Col or Act i onLi st ener i mpl ement s Act i onLi st ener {
Col or backgr oundCol or ;

publ i c Col or Act i onLi st ener ( Col or aCol or ) {
backgr oundCol or = aCol or ;
}

publ i c voi d act i onPer f or med( Act i onEvent event ) {
set Backgr ound( backgr oundCol or ) ;
r epai nt ( ) ; / / Show ef f ect of col or change
}
}
}



Java Graphics
Gr aphi cs i n J ava i s made r el at i vel y easy by many st andar d l i br ar y
cal l s t hat ar e not i ncl uded i n many l anguages.

The paint method has a graphics object as an argument
publ i c voi d pai nt ( Gr aphi cs di spl ay ) {
di spl ay. dr awSt r i ng( " Const ant " , 30, 40 ) ;
}

The graphics class contains methods for drawing


UIU Lecture 9b, CSI 211
6/7



Some Graphics Methods

clearRect(int, int, int, int)
copyArea(int, int, int, int, int, int)
draw3DRect(int, int, int, int, boolean)
fillOval(int, int, int, int)
fillRect(int, int, int, int)
drawChars(char[], int, int, int, int) etc.

Drawing
This example shows some methods in Graphics that we can use to draw on the screen.

i mpor t j ava. awt . *;
cl ass Dr awi ng ext ends J Fr ame {
publ i c Dr awi ng ( i nt Wi dt hI nPi xel s, i nt hei ght I nPi xel s ) {
set Ti t l e( " Dr awi ng" ) ;
set Si ze( Wi dt hI nPi xel s, hei ght I nPi xel s ) ;
set Locat i on( 40, 40) ;
set Backgr ound( Col or . gr een) ;
show( ) ;
}
publ i c voi d pai nt ( Gr aphi cs di spl ay ) {
di spl ay. set Col or ( Col or . dar kGr ay ) ;
i nt x = 50; i nt y = 30;
i nt wi dt h = 40; i nt hei ght = 40;
di spl ay. dr awOval ( x, y, wi dt h, hei ght ) ;
x = 100;
di spl ay. dr awRect ( x, y, wi dt h, hei ght ) ;
x = 150;
di spl ay. f i l l Rect ( x, y, wi dt h, hei ght ) ;
x = 200;
bool ean r ai sed = t r ue;
di spl ay. dr aw3DRect ( x, y, wi dt h, hei ght , r ai sed ) ;

di spl ay. set Col or ( Col or . r ed ) ;
i nt x1 = 50; i nt y1 = 60;
i nt x2 = 200; i nt y2 = 60;
di spl ay. dr awLi ne( x1, y1, x2, y2 ) ;
Di mensi on si ze = get Si ze( ) ;
di spl ay. dr awRect ( 0, 0, si ze. wi dt h - 1, si ze. hei ght - 1 ) ;
}
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) {
new Dr awi ng( 300, 100 ) ;
}
}




UIU Lecture 9b, CSI 211
7/7



Output





*************** End of Lecture 9b **************

UIU Lecture 10a, CSI 211
1/13
United International University

Course: CSI 211
Course Title: Object Oriented Programming
Lecture 10a: Layouts, Containers, Events, Event Handling,.


Layouts
Need to specify where items will appear in a window that changes size
Layouts provide a flexible way to place items in a window without specifying
coordinates
Layouts determine place components will be seen on the screen

FlowLayout Example

Displays components left to right, top to bottom. Note how the buttons in the window
"flow" as the window's shape is changed.
i mpor t j ava. awt . *;
cl ass Fl owLayout Exampl e ext ends Fr ame {

publ i c Fl owLayout Exampl e( i nt wi dt h, i nt hei ght ) {
set Ti t l e( " Fl ow Exampl e" ) ;
set Si ze( wi dt h, hei ght ) ;
set Layout ( new Fl owLayout ( Fl owLayout . LEFT) ) ;

f or ( i nt l abel = 1; l abel < 10; l abel ++ )
add( new But t on( St r i ng. val ueOf ( l abel ) ) ) ;
show( ) ;
}
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) {
new Fl owLayout Exampl e( 175, 100 ) ;
}
}
Output


UIU Lecture 10a, CSI 211
2/13



ii) BorderLayout
Default layout for a frame and divides area into named regions:




Note how the layout deals the buttons as the window is resized.

i mpor t j ava. awt . *;
cl ass Bor der Layout Exampl e ext ends Fr ame {

publ i c Bor der Layout Exampl e( i nt wi dt hI nPi xel s,
i nt hei ght I nPi xel s ) {
set Ti t l e( " Bor der Layout Exampl e" ) ;
set Si ze( wi dt hI nPi xel s, hei ght I nPi xel s ) ;
set Layout ( new Bor der Layout ( ) ) ;

add( new But t on( " Nor t h" ) , Bor der Layout . NORTH ) ;
add( new But t on( " Cent er " ) , Bor der Layout . CENTER ) ;
add( new But t on( " East " ) , Bor der Layout . EAST ) ;
add( new But t on( " West " ) , Bor der Layout . WEST ) ;
add( new But t on( " Sout h" ) , Bor der Layout . SOUTH ) ;
show( ) ;
}

publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) {
new Bor der Layout Exampl e( 175, 100 ) ;
}
}
Output


UIU Lecture 10a, CSI 211
3/13





iii) GridLayout

A simple grid example.
i mpor t j ava. awt . *;
cl ass Gr i dLayout Exampl e ext ends Fr ame {

publ i c Gr i dLayout Exampl e( i nt wi dt hI nPi xel s, i nt hei ght I nPi xel s ) {
set Ti t l e( " Gr i d Exampl e" ) ;
set Si ze( wi dt hI nPi xel s, hei ght I nPi xel s ) ;
i nt number Of Rows = 4;
i nt number Of Col umns = 3;
set Layout ( new Gr i dLayout ( number Of Rows,
number Of Col umns ) ) ;

f or ( i nt l abel = 1; l abel < 13; l abel ++ )
add( new But t on( St r i ng. val ueOf ( l abel ) ) ) ;
show( ) ;
}

publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) {
new Gr i dLayout Exampl e( 175, 100 ) ;
}
}







UIU Lecture 10a, CSI 211
4/13
iv) GridBagLayout
The Gr i dBagLayout manager is about three times more flexible than any of the
other standard layout managers.
Unfortunately, Gr i dBagLayout is also about nine times harder to use.
The basic idea is that you chop up the window into grids, then you specify for
each component which cell to start and end in. You can also specify how objects
stretch when there is extra room and alignment within cells.
The basic steps to using Gr i dBagLayout are:
Set the layout, saving a reference to it.
Gr i dBagLayout l ayout = new Gr i dBagLayout ( ) ;
set Layout ( l ayout ) ;
Allocate a GridBagConstraints object.
Gr i dBagConst r ai nt s const r ai nt s =
new Gr i dBagConst r ai nt s( ) ;
Set up the GridBagConstraints for component 1.
const r ai nt s. gr i dx = x1;
const r ai nt s. gr i dy = y1;
const r ai nt s. gr i dwi dt h = wi dt h1;
const r ai nt s. gr i dhei ght = hei ght 1;
. . .
Add the first component to the window, including constraints.
add( component 1, const r ai nt s) ;
Repeat the last two steps for each remaining component.
Example

GridBagTest.java

publ i c cl ass Gr i dBagTest ext ends J Panel {
pr i vat e J Text Ar ea t ext Ar ea;
pr i vat e J But t on bSaveAs, bOk, bExi t ;
pr i vat e J Text Fi el d f i l eFi el d;
pr i vat e Gr i dBagConst r ai nt s c;

publ i c Gr i dBagTest ( ) {
set Layout ( new Gr i dBagLayout ( ) ) ;
set Bor der ( Bor der Fact or y. cr eat eEt chedBor der ( ) ) ;


UIU Lecture 10a, CSI 211
5/13
t ext Ar ea = new J Text Ar ea( 12, 40) ; / / 12 r ows, 40 col s
bSaveAs = new J But t on( " Save As" ) ;
f i l eFi el d = new J Text Fi el d( " C: \ \ Document . t xt " ) ;
bOk = new J But t on( " OK" ) ;
bExi t = new J But t on( " Exi t " ) ;
c = new Gr i dBagConst r ai nt s( ) ;

/ / Text Ar ea.
c. gr i dx = 0;
c. gr i dy = 0;
c. gr i dwi dt h = Gr i dBagConst r ai nt s. REMAI NDER;
c. gr i dhei ght = 1;
c. wei ght x = 1. 0;
c. wei ght y = 1. 0;
c. f i l l = Gr i dBagConst r ai nt s. BOTH;
c. i nset s = new I nset s( 2, 2, 2, 2) ; / / t , l , b, r
add( t ext Ar ea, c) ;

/ / Save As But t on.
c. gr i dx = 0;
c. gr i dy = 1;
c. gr i dwi dt h = 1;
c. gr i dhei ght = 1;
c. wei ght x = 0. 0;
c. wei ght y = 0. 0;
c. f i l l = Gr i dBagConst r ai nt s. VERTI CAL;
add( bSaveAs, c) ;

/ / Fi l ename I nput ( Text f i el d) .
c. gr i dx = 1;
c. gr i dwi dt h = Gr i dBagConst r ai nt s. REMAI NDER;
c. gr i dhei ght = 1;
c. wei ght x = 1. 0;
c. wei ght y = 0. 0;
c. f i l l = Gr i dBagConst r ai nt s. BOTH;
add( f i l eFi el d, c) ;

/ / OK But t on.
c. gr i dx = 2;
c. gr i dy++;
c. gr i dwi dt h = 1;
c. gr i dhei ght = 1;
c. wei ght x = 0. 0;
c. wei ght y = 0. 0;
c. f i l l = Gr i dBagConst r ai nt s. NONE;
add( bOk, c) ;
/ / Exi t But t on.
c. gr i dx = 3;
c. gr i dwi dt h = 1;
c. gr i dhei ght = 1;
c. wei ght x = 0. 0;
c. wei ght y = 0. 0;
c. f i l l = Gr i dBagConst r ai nt s. NONE;
add( bExi t , c) ;

/ / Fi l l er so Col umn 1 has nonzer o wi dt h.
Component f i l l er = Box. cr eat eRi gi dAr ea( new Di mensi on( 1, 1) ) ;

UIU Lecture 10a, CSI 211
6/13
c. gr i dx = 1;
c. wei ght x = 1. 0;
add( f i l l er , c) ;
}

publ i c st at i c voi d mai n( St r i ng[ ] ar gs) {
Wi ndowUt i l i t i es. set Nat i veLookAndFeel ( ) ;
J Fr ame f r ame = new J Fr ame( " Gr i gBagLayout Test " ) ;
f r ame. set Cont ent Pane( new Gr i dBagTest ( ) ) ;
f r ame. addWi ndowLi st ener ( new Exi t Li st ener ( ) ) ;
f r ame. pack( ) ;
f r ame. set Vi si bl e( t r ue) ;
}
}






Containers

Panels allow use of one layout inside of another layout.
A panel is a container, so it holds components.
A panel has a layout. The default layout for all panels is FlowLayout.
Mixing layouts increases the flexibility of layouts. In the example below, a panel
full of buttons is added to the north region of a Borderlayout.


UIU Lecture 10a, CSI 211
7/13
i mpor t j ava. awt . *;
cl ass Panel Exampl e ext ends Fr ame {

publ i c Panel Exampl e( i nt wi dt hI nPi xel s, i nt hei ght I nPi xel s ) {
set Ti t l e( " Panel Exampl e" ) ;
set Si ze( wi dt hI nPi xel s, hei ght I nPi xel s ) ;
set Layout ( new Bor der Layout ( ) ) ;

Panel but t onDi spl ay = new Panel ( ) ;
but t onDi spl ay. set Layout ( new Fl owLayout ( ) ) ;

f or ( i nt l abel = 1; l abel < 6; l abel ++ )
but t onDi spl ay. add( new But t on( St r i ng. val ueOf ( l abel ) ) ) ;
add( but t onDi spl ay, Bor der Layout . NORTH ) ;
add( new But t on( " Cent er " ) , Bor der Layout . CENTER) ;
add( new Scr ol l bar ( Scr ol l bar . VERTI CAL ) , Bor der Layout . EAST ) ;
add( new Scr ol l bar ( Scr ol l bar . HORI ZONTAL ) , Bor der Layout . SOUTH ) ;
show( ) ;
}

publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) {
new Panel Exampl e( 175, 100 ) ;
}
}




Result of Panel Example





Not e t hat t he but t ons do not wr ap t o second r ow of but t ons even
t hough t hey ar e i n a Fl owLayout ! The Fl owLayout i s i n nor t h par t
of a Bor der Layout . Onl y one r ow i s avai l abl e!

UIU Lecture 10a, CSI 211
8/13

Canvas
A canvas is a rectangular region in which you can draw on.
Canvas Methods
o addNotify()
o Creates the peer of the canvas.
o paint(Graphics)
o Paints the canvas in the default background color
Example #1
cl ass Si mpl eCanvas ext ends Canvas{
publ i c voi d pai nt ( Gr aphi cs dr awOnMe ) {
i nt st ar t X = 0;
i nt st ar t Y = 0;
i nt endX = 30;
i nt endY = 30;
dr awOnMe. dr awLi ne( st ar t X, st ar t Y, endX, endY ) ;
i nt wi dt h = 5;
i nt hei ght = 5;
dr awOnMe. dr awOval ( endX, endY, wi dt h, hei ght ) ;
}
}
Out put




Example #2
cl ass CanvasExampl e ext ends Fr ame {
publ i c CanvasExampl e( i nt wi dt hI nPi xel s, i nt hei ght I nPi xel s ) {
set Ti t l e( " Canvas Exampl e" ) ;
set Si ze( wi dt hI nPi xel s, hei ght I nPi xel s ) ;
set Layout ( new Bor der Layout ( ) ) ;

Panel but t onDi spl ay = new Panel ( ) ;
but t onDi spl ay. set Layout ( new Fl owLayout ( ) ) ;

f or ( i nt l abel = 1; l abel < 6; l abel ++ )
but t onDi spl ay. add( new But t on( St r i ng. val ueOf ( l abel ) ) ) ;
add( but t onDi spl ay, Bor der Layout . NORTH ) ;
add( new Si mpl eCanvas( ) , Bor der Layout . CENTER ) ;
add( new Scr ol l bar ( Scr ol l bar . VERTI CAL ) , Bor der Layout . EAST ) ;
add( new Scr ol l bar ( Scr ol l bar . HORI ZONTAL ) ,
Bor der Layout . SOUTH ) ;
show( ) ;

UIU Lecture 10a, CSI 211
9/13
}

publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) {
new CanvasExampl e( 175, 150 ) ;
}
}

Out put






Event Model
GUI s must handl e event s l i ke mouse cl i cks, mouse movement s,
scr ol l i ng of a wi ndow.
Exampl e - Wi ndow Event sTypes of Event s

wi ndowAct i vat ed( Wi ndowEvent )
I nvoked when a wi ndow i s act i vat ed.

wi ndowCl osed( Wi ndowEvent )
I nvoked when a wi ndow has been cl osed.

wi ndowCl osi ng( Wi ndowEvent )

Examples
WindowListener

This example shows how to use a WindowListener to quit an application. Note that you
cannot use System.exit(0) in an applet.
cl ass Qui t abl eAppl i cat i on1 ext ends Fr ame
{
publ i c Qui t abl eAppl i cat i on1( i nt l ef t , i nt t op, i nt wi dt h, i nt
hei ght , St r i ng t i t l e )

UIU Lecture 10a, CSI 211
10/13
{
super ( t i t l e ) ;
set Si ze( wi dt h, hei ght ) ;
set Locat i on( l ef t , t op) ;
Label hel l o = new Label ( " Hel l o Wor l d" , Label . CENTER) ;
add( hel l o, Bor der Layout . CENTER ) ;
addWi ndowLi st ener ( new Qui t Wi ndow( t hi s ) ) ;
show( ) ;
}
}
cl ass Qui t Wi ndow i mpl ement s Wi ndowLi st ener
{
Fr ame myWi ndow;
publ i c Qui t Wi ndow( Fr ame aWi ndow )
{
myWi ndow = aWi ndow;
}
publ i c voi d wi ndowCl osi ng( Wi ndowEvent event )
{
myWi ndow. di spose( ) ;
Syst em. exi t ( 0) ;
}

publ i c voi d wi ndowAct i vat ed( Wi ndowEvent event ) {};
publ i c voi d wi ndowCl osed( Wi ndowEvent event ) {};
publ i c voi d wi ndowDeact i vat ed( Wi ndowEvent event ) {};
publ i c voi d wi ndowDei coni f i ed( Wi ndowEvent event ) {};
publ i c voi d wi ndowI coni f i ed( Wi ndowEvent event ) {};
publ i c voi d wi ndowOpened( Wi ndowEvent event ) {};
}


Listening to Yourself

i mpor t j ava. awt . event . Wi ndowAdapt er ;
i mpor t j ava. awt . event . Wi ndowEvent ;
i mpor t j ava. awt . event . Wi ndowLi st ener ;
i mpor t j ava. awt . Fr ame;
i mpor t j ava. awt . Label ;
cl ass Qui t abl eAppl i cat i on4 ext ends Fr ame
{
publ i c Qui t abl eAppl i cat i on4( i nt l ef t , i nt t op, i nt wi dt h, i nt
hei ght , St r i ng t i t l e )
{
super ( t i t l e ) ;
set Si ze( wi dt h, hei ght ) ;
set Locat i on( l ef t , t op) ;
Label hel l o = new Label ( " Hel l o Wor l d" , Label . CENTER) ;
add( hel l o, Bor der Layout . CENTER ) ;
addWi ndowLi st ener ( new Wi ndowAdapt er ( ) {
publ i c voi d wi ndowCl osi ng( Wi ndowEvent event )
{
qui t ( ) ;
}
}

UIU Lecture 10a, CSI 211
11/13
) ;
show( ) ;
}
publ i c voi d qui t ( )
{
di spose( ) ;
Syst em. exi t ( 0 ) ;
}
}

AWT Events
AWTEvent i s t he par ent cl ass of al l AWT event cl asses.
Her e ar e t he AWT event s, t he r el at ed l i st ener s and t he l i st ener
met hods.
Event Class Listener Interface Listener Methods
ActionEvent ActionListener actionPerformed()
ItemEvent ItemListener itemStateChanged()
MouseEvent MouseListener mouseClicked()
mouseEntered()
mousePressed()
mouseReleased()
MouseMotionListener mouseDragged()
mouseMoved()



The following table lists the events supported by each component and when the
event is generated. Note that all other components are subclass of the Component
class.

Component Events Meaning
Button ActionEvent Button clicked
Checkbox ItemEvent Item selected or deselected
TextField ActionEvent User finished editing text



Event Listening Example

The following listeners will be used to listen to all the events that occur to a button. The
main program and output come after the listeners.

UIU Lecture 10a, CSI 211
12/13
i mpor t j ava. awt . *;
i mpor t j ava. awt . event . *;

Button

cl ass But t onSnooper i mpl ement s Act i onLi st ener {
publ i c voi d act i onPer f or med( Act i onEvent event ) {
Syst em. out . pr i nt l n( " But t on pr essed" ) ;
}
}

Mouse

cl ass MouseSnooper i mpl ement s MouseLi st ener {
publ i c voi d mouseCl i cked( MouseEvent event ) {
Syst em. out . pr i nt l n( " Mouse cl i cked" ) ;
}

publ i c voi d mousePr essed( MouseEvent event ) {
Syst em. out . pr i nt l n( " Mouse pr essed" ) ;
}
publ i c voi d mouseRel eased( MouseEvent event ) {
Syst em. out . pr i nt l n( " Mouse r el eased" ) ;
}
publ i c voi d mouseEnt er ed( MouseEvent event ) {
But t on cur r ent But t on = ( But t on) event . get Component ( ) ;
Syst em. out . pr i nt l n( " Mouse ent er ed " + cur r ent But t on. get Label ( )
) ;
}
publ i c voi d mouseExi t ed( MouseEvent event ) {
Syst em. out . pr i nt l n( " Mouse exi t ed" ) ;
}
}


Mouse Motion

cl ass MouseMot i onSnooper i mpl ement s MouseMot i onLi st ener {
publ i c voi d mouseDr agged( MouseEvent event ) {
Syst em. out . pr i nt l n( " Mouse dr agged" ) ;
}

publ i c voi d mouseMoved( MouseEvent event ) {
Syst em. out . pr i nt l n( " Mouse moved, i s at : " + event . get Poi nt ( ) ) ;
}
}
cl ass FocusSnooper i mpl ement s FocusLi st ener {
publ i c voi d f ocusGai ned( FocusEvent event ) {
But t on cur r ent But t on = ( But t on) event . get Component ( ) ;

Syst em. out . pr i nt ( cur r ent But t on. get Label ( ) + " gai ned f ocus" ) ;
i f ( event . i sTempor ar y( ) )
Syst em. out . pr i nt l n( " : t empor ar y" ) ;
el se
Syst em. out . pr i nt l n( ) ;
}

UIU Lecture 10a, CSI 211
13/13

publ i c voi d f ocusLost ( FocusEvent event ) {
But t on cur r ent But t on = ( But t on) event . get Component ( ) ;

Syst em. out . pr i nt ( cur r ent But t on. get Label ( ) + " l ost f ocus" ) ;
i f ( event . i sTempor ar y( ) )
Syst em. out . pr i nt l n( " : t empor ar y" ) ;
el se
Syst em. out . pr i nt l n( ) ;
}
}

Event Application

cl ass Event Exampl e ext ends Fr ame
{
But t on a = new But t on( " A" ) ;
But t on b = new But t on( " B" ) ;

publ i c Event Exampl e( i nt wi dt hI nPi xel s, i nt hei ght I nPi xel s )
{
set Ti t l e( " Event Exampl e" ) ;
set Si ze( wi dt hI nPi xel s, hei ght I nPi xel s ) ;
add( a, Bor der Layout . NORTH ) ;
add( b, Bor der Layout . CENTER ) ;

a. addAct i onLi st ener ( new But t onSnooper ( ) ) ;
a. addMouseLi st ener ( new MouseSnooper ( ) ) ;
a. addMouseMot i onLi st ener ( new MouseMot i onSnooper ( ) ) ;
a. addFocusLi st ener ( new FocusSnooper ( ) ) ;
a. addKeyLi st ener ( new KeySnooper ( ) ) ;

b. addAct i onLi st ener ( new But t onSnooper ( ) ) ;
b. addMouseLi st ener ( new MouseSnooper ( ) ) ;
b. addMouseMot i onLi st ener ( new MouseMot i onSnooper ( ) ) ;
b. addFocusLi st ener ( new FocusSnooper ( ) ) ;
b. addKeyLi st ener ( new KeySnooper ( ) ) ;

show( ) ;
}

publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) {
Event Exampl e wi ndow = new Event Exampl e( 200, 50) ;
}
}




*************** End of Lecture 10a **************

UIU Lecture 11a, CSI 211
1/7
United International University

Course: CSI 211
Course Title: Object Oriented Programming
Lecture 11a: GUI Components

Handling Events in GUI Controls

How A mouse event handler works

public class MouseEvent sDemo extends Fr ame implements
MouseLi st ener , MouseMot i onLi st ener {
Text Fi el d t f ;
public MouseEvent sDemo( St r i ng t i t l e) {
super( t i t l e) ;
t f = new Text Fi el d( 60) ;
addMouseLi st ener ( this) ;
}
public void l aunchFr ame( ) {
/ * Add component s t o t he f r ame */
add( t f , Bor der Layout . SOUTH) ;
set Si ze( 300, 300) ;
set Vi si bl e( true) ;
}
public void mouseCl i cked( MouseEvent me) {
St r i ng msg = " Mouse cl i cked. " ;
t f . set Text ( msg) ;
}
public void mouseEnt er ed( MouseEvent me) {
St r i ng msg = " Mouse ent er ed component . " ;
t f . set Text ( msg) ;
}
public void mouseExi t ed( MouseEvent me) {
St r i ng msg = " Mouse exi t ed component . " ;
t f . set Text ( msg) ;
}
public void mousePr essed( MouseEvent me) {
St r i ng msg = " Mouse pr essed. " ;
t f . set Text ( msg) ;
}
public void mouseRel eased( MouseEvent me) {
St r i ng msg = " Mouse r el eased. " ;
t f . set Text ( msg) ;
}
public void mouseDr agged( MouseEvent me) {
St r i ng msg = " Mouse dr agged at " + me. get X( )
+ " , " + me. get Y( ) ;
t f . set Text ( msg) ;
}
public void mouseMoved( MouseEvent me) {
St r i ng msg = " Mouse moved at " + me. get X( )
+ " , " + me. get Y( ) ;
t f . set Text ( msg) ;
}

UIU Lecture 11a, CSI 211
2/7
public static void mai n( St r i ng ar gs[ ] ) {
MouseEvent sDemo med =
new MouseEvent sDemo( " Mouse Event s Demo" ) ;
med. l aunchFr ame( ) ;
}
}

Output



How An item listener works


publ i c cl ass CheckBox1 ext ends J Appl et i mpl ement s I t emLi st ener {
/ * Decl ar at i on */
pr i vat e Cont ai ner Panel ;
pr i vat e Layout Manager Layout ;
pr i vat e J CheckBox Bol d;
pr i vat e J CheckBox I t al i c;
pr i vat e J Text Fi el d Resul t ;

publ i c CheckBox1 ( ) {
/ * I nst ant i at i on */
Layout = new Fl owLayout ( ) ;
Bol d = new J CheckBox ( " Bol d" ) ;
I t al i c = new J CheckBox ( " I t al i c" , t r ue) ;
Resul t = new J Text Fi el d ( " " , 25) ;

Panel = get Cont ent Pane ( ) ;

/ * Locat i on */
Panel . set Layout ( Layout ) ;
Panel . add ( Bol d) ;

UIU Lecture 11a, CSI 211
3/7
Panel . add ( I t al i c) ;
Panel . add ( Resul t ) ;
Panel . set Backgr ound ( Col or . yel l ow) ;

/ * Conf i gur at i on */
Bol d. addI t emLi st ener ( t hi s) ;
I t al i c. addI t emLi st ener ( t hi s) ;
Resul t . set Edi t abl e ( f al se) ;

/ * Decor at i on */
Bol d. set Backgr ound ( Col or . yel l ow) ;
I t al i c. set Backgr ound ( Col or . yel l ow) ;

/ * I ni t i al i zat i on */
set St at e ( ) ;
}

pr i vat e voi d set St at e ( ) {
St r i ng Text ;
i nt St yl e;
Font ShowFont ;

Text = " 14 poi nt " ;
St yl e = 0;
i f ( Bol d. i sSel ect ed( ) ) {
St yl e = St yl e | Font . BOLD;
Text += " bol df ace" ;
} el se {
Text += " r egul ar wei ght " ;
}
i f ( I t al i c. i sSel ect ed( ) ) {
St yl e = St yl e | Font . I TALI C;
Text += " I t al i c" ;
} el se {
Text += " Roman" ;
}
Text += " f ont " ;
ShowFont = new Font ( " SansSer i f " , St yl e, 14) ;
Resul t . set Font ( ShowFont ) ;
Resul t . set Text ( Text ) ;
}

publ i c voi d i t emSt at eChanged( I t emEvent e) {
set St at e ( ) ;
}

}



Output

UIU Lecture 11a, CSI 211
4/7





Checkbox AWT component
Checkboxes.java
i mpor t j ava. awt . *;

publ i c cl ass Checkboxes ext ends Cl oseabl eFr ame {
publ i c st at i c voi d mai n( St r i ng[ ] ar gs) {
new Checkboxes( ) ;
}

publ i c Checkboxes( ) {
super ( " Checkboxes" ) ;
set Font ( new Font ( " SansSer i f " , Font . BOLD, 18) ) ;
set Layout ( new Gr i dLayout ( 0, 2) ) ;
Checkbox box;
f or ( i nt i =0; i <12; i ++) {
box = new Checkbox( " Checkbox " + i ) ;
i f ( i %2 == 0) {
box. set St at e( t r ue) ;
}
add( box) ;
}
pack( ) ;
set Vi si bl e( t r ue) ;
}
}

UIU Lecture 11a, CSI 211
5/7


Choice - Drop-down Lists -AWT
Lists.java
i mpor t j ava. awt . *;

publ i c cl ass Li st s ext ends Cl oseabl eFr ame {
publ i c st at i c voi d mai n( St r i ng[ ] ar gs) {
new Li st s( ) ;
}

publ i c Li st s( ) {
super ( " Li st s" ) ;
set Layout ( new Fl owLayout ( ) ) ;
set Backgr ound( Col or . l i ght Gr ay) ;
set Font ( new Font ( " SansSer i f " , Font . BOLD, 18) ) ;
Li st l i st 1 = new Li st ( 3, f al se) ;
l i st 1. add( " Vani l l a" ) ;
l i st 1. add( " Chocol at e" ) ;
l i st 1. add( " St r awber r y" ) ;
add( l i st 1) ;
Li st l i st 2 = new Li st ( 3, t r ue) ;
l i st 2. add( " Col or ed Spr i nkl es" ) ;
l i st 2. add( " Cashews" ) ;
l i st 2. add( " Ki wi " ) ;
add( l i st 2) ;
pack( ) ;
set Vi si bl e( t r ue) ;
}
}






UIU Lecture 11a, CSI 211
6/7



Threads and GUI Components


Swi ng f ol l ows t he f ami l i ar AWT event model and uses a si ngl e-
t hr eaded desi gn f or updat i ng component s.
As a consequence of t he event model , t wo gener al r ul es appl y f or
r obust GUI desi gn:

1. If tasks in the event handling method require considerable CPU time, then
execute these time-intensive tasks in a separate thread. Freeing the event
dispatch thread to process other queued events yields a more responsive user
interface.

2. Make changes to the state of a realized (visible) Swing component only within
the event dispatch thread and not within a user-defined thread.
Poor design

/ / Poor l y desi gned event handl er f or St ar t but t on.
publ i c voi d act i onPer f or med( Act i onEvent event ) {

/ / Change t o l abel i s ok her e because i t i s execut ed
/ / on t he event di spat ch t hr ead.
l abel . set Text ( " Tr ansf er r i ng " + f i l ename) ;

/ / Tr ansf er f i l e t o ser ver - t i me i nt ensi ve.
t r ansf er Fi l e( f i l ename) ;

/ / Ok t o change l abel her e al so, execut ed on
/ / event di spat ch t hr ead.
l abel . set Text ( " Tr ansf er compl et ed. " ) ;
}






UIU Lecture 11a, CSI 211
7/7
Better design


I mpr oved event handl er . Ti me- i nt ensi ve t ask i s
/ / moved t o a separ at e t hr ead.
publ i c voi d act i onPer f or med( Act i onEvent event ) {
/ / Change t o l abel i s ok her e si nce i t i s execut ed
/ / on t he event t hr ead.
l abel . set Text ( " Tr ansf er r i ng " + f i l ename) ;

/ / Tr ansf er r i ng t he f i l e i s t i me i nt ensi ve, so t he
/ / t ask i s per f or med i n a separ at e t hr ead t o per mi t
/ / pr ocessi ng of ot her event s on t he event queue.
Thr ead t = new Fi l eTr ansf er ( f i l ename, l abel ) ;
t . st ar t ( ) ;
}


Fi l eTr ansf er ,
/ / I mpr oper l y desi gned t hr ead cl ass - updat e
/ / of Swi ng component i s not t hr ead saf e.
publ i c cl ass Fi l eTr ansf er ext ends Thr ead {
pr i vat e St r i ng f i l ename;
pr i vat e J Label = l abel ;

publ i c Fi l eTr ansf er ( St r i ng f i l ename, J Label l abel ) {
t hi s. f i l ename = f i l ename;
t hi s. l abel = l abel ;
}

publ i c voi d r un( ) {
/ / Tr ansf er f i l e t o ser ver . Lengt hy pr ocess.
doTr ansf er ( . . . ) ;

/ / Updat e of l abel i s not ok. Updat e i s not
/ / execut ed on t he event di spat ch t hr ead.
l abel . set Text ( " Tr ansf er compl et e. " ) ;
}
}




*************** End of Lecture 11a **************

UIU Lecture 11a, CSI 211
1/7
United International University

Course: CSI 211
Course Title: Object Oriented Programming
Lecture 11b: Applet


Applet
The HTML : HelloApplet.html

<HTML>
<HEAD>
<TI TLE>Hel l oAppl et </ TI TLE>
</ HEAD>
<BODY>
<HR>
Thi s i s t he f i r st Appl et <P>
<APPLET
code=" Hel l oAppl et . cl ass" wi dt h=100 hei ght =100>
</ APPLET><BR>
The End
<HR>
</ BODY>
</ HTML>


The Java Code: HelloApplet.java
i mpor t j ava. awt . *;
i mpor t j ava. appl et . Appl et ;
publ i c cl ass Hel l oAppl et ext ends Appl et
{
publ i c voi d i ni t ( ) {
r epai nt ( ) ;
}

publ i c voi d pai nt ( Gr aphi cs g ) {
g. dr awSt r i ng( " Hel l o Wor l d! " , 30, 30 ) ;
}
}


Command line-
C:\>appletviewer HellloApplet.html

UIU Lecture 11a, CSI 211
2/7
Output
Note: all examples are done using the applet viewer




Applet Methods

init()
Called by the browser or applet viewer when an applet is loaded into the system. This is
used to replace the functionality of constructor. This method is called only once in the life
of an applet object.

start()
Called by the browser or applet viewer to inform an applet that it should start its
execution. It is called automatically after the init() method is called. It is also called when
the user returns to the page containing the applet, after viewing other pages. Start is often
used to start threads and animation. This method can be called more than once in the life
of an applet object.

stop()
Called by the browser or applet viewer to inform an applet that it should stop its
execution. This is called when the user moves off to another page. Use this to stop
animations, threads, and playing audio files. If you do not use animation, threads or audio
files you normally don't need to implement stop().. This method can be called more than
once in the life of an applet object.



UIU Lecture 11a, CSI 211
3/7
destroy()
Called by the browser or applet viewer to inform this applet that it is being unloaded. Use
this method to reclaim any non-memory-dependent destroy resources that it has allocated
(like graphics contexts). This method is called only once in the life of an applet object.

Example

This example just displays when the basic applet methods are run in an applet. The output
is displayed in a TextArea. In order to save space on the slide, I will only display the
applet part of the HTML. This does work with the applet viewer and broswers, although
it is not proper HTML.

HTML
<APPLET
CODE=" Basi cEvent Appl et . cl ass" WI DTH=300 HEI GHT=200>
</ APPLET>

Java Code
i mpor t j ava. awt . *;
i mpor t j ava. appl et . Appl et ;
publ i c cl ass Basi cEvent Appl et ext ends Appl et
{
Text Ar ea messages = new Text Ar ea( 8, 30) ;

publ i c Basi cEvent Appl et ( ) {
messages. append( " Const r uct or \ n" ) ;
}

publ i c voi d i ni t ( ) {
add( messages ) ;
messages. append( " I ni t \ n" ) ;
}

publ i c voi d st ar t ( ) { messages. append( " St ar t \ n" ) ; }
publ i c voi d st op( ) { messages. append( " St op\ n" ) ; }
publ i c voi d dest r oy( ) { messages. append( " Dest r oy\ n" ) ; }

publ i c voi d pai nt ( Gr aphi cs g ) {messages. append( " Pai nt \ n" ) ; }
}



Output
Note: all examples are done using the applet viewer

UIU Lecture 11a, CSI 211
4/7




Alternative Text

Some browsers do not support applets. You should provide alternative text to be
displayed in such browsers. The tag below provides such text.
<APPLET
CODE=" Basi cEvent Appl et . cl ass" WI DTH=300 HEI GHT=200>
Your br owser does <B>not </ B> suppor t appl et s! So you can
not use my gr eat appl et .
</ APPLET>


Applet Parameters
This example shows how to pass information to an applet from the html page. The
getParameter() method will read arguments with the param tag. It also seems to read the
width & height. The methods getAppletInfo() & getParameterInfo() are used by the
applet viewer to provide the user with information about the applet.

HTML
<APPLET
CODE=" Par amet er Appl et . cl ass" WI DTH=300 HEI GHT=200>
<PARAM NAME=" name" VALUE=" Roger " >
<PARAM NAME=" your Hei ght " VALUE=" 5" >
</ APPLET>

UIU Lecture 11a, CSI 211
5/7
Java Code
i mpor t j ava. awt . *;
i mpor t j ava. appl et . Appl et ;
publ i c cl ass Par amet er Appl et ext ends Appl et {
Text Ar ea messages = new Text Ar ea( 8, 20) ;

publ i c voi d i ni t ( ) {
add( messages ) ;
St r i ng name = get Par amet er ( " name" ) ;
i nt hei ght =
I nt eger . val ueOf ( get Par amet er ( " your Hei ght " ) ) . i nt Val ue( ) ;
messages. append( " name: " + name + " \ n" ) ;
messages. append( " hei ght : " + hei ght + " \ n" ) ; }
publ i c St r i ng get Appl et I nf o( ) {
r et ur n " Thi s appl et shows how t o pass i nf or mat i on" +
" f r omt he ht ml document t o t he appl et " ; }

publ i c St r i ng[ ] [ ] get Par amet er I nf o( ) {
r et ur n new St r i ng[ ] [ ] {
{ " name" , " st r i ng" , " your name" },
{ " your Hei ght " , " i nt " , " your hei ght " }
};
}
}


Output
Note: all examples are done using the applet viewer




Multiple Files
An applet may require more than one .class file, or it may require a sound file or image
files. By default, all files are loaded from the same location as the .html file that refers to
the applet. In the following example, the applet requires the file AnotherClass.class to

UIU Lecture 11a, CSI 211
6/7
run. It is downloaded from the same location as the .html file and the
MultipleFilesApplet.class file.

HTML
<APPLET
CODE=" Mul t i pl eFi l esAppl et . cl ass" WI DTH=300 HEI GHT=200>
</ APPLET>

Java Code
i mpor t j ava. awt . *;
i mpor t j ava. appl et . Appl et ;
publ i c cl ass Mul t i pl eFi l esAppl et ext ends Appl et
{
publ i c voi d i ni t ( ) {
r epai nt ( ) ;
}
publ i c voi d pai nt ( Gr aphi cs di spl ay ) {
Anot her Cl ass t est = new Anot her Cl ass( ) ;
di spl ay. dr awSt r i ng( t est . name( ) , 20, 20 ) ;
}
}
publ i c cl ass Anot her Cl ass {
publ i c St r i ng name( ) {
r et ur n " Roger " ;
}
}

JAR Files
The files required by an applet can be placed into a jar file. A jar file is a compressed file
(zip algorithm) with a manifest (list of contents). This can speed up the transfer of the
applet in two ways. First, the file is compressed. Second, if requires only one interaction
with the web server to obtain all the needed files. The example below, shows how create
and access a jar file for the applet .

The basic syntax for creating a jar file is:
j ar - cf j ar Fi l eName. j ar f i l e1, f i l e2, . . . , f i l eN

where file1, ..., fileN are the files to put into the jar file.

The following command creates the file myJ ar.jar for the example on the previous slide.

UIU Lecture 11a, CSI 211
7/7

j ar - cf myJ ar . j ar Anot her Cl ass. cl ass Mul t i pl eFi l esAppl et . cl ass

The following applet tag tells the browser/appleviewer to also look into the jar file
myjar.jar to find any files needed by the applet. The jar file will be loaded from the same
location as the html file. You can specify more than one jar file by separating the file
names with commas: archive="jar1.jar, jar2.jar".
<APPLET
ARCHI VE=" myJ ar . j ar "
CODE=" Mul t i pl eFi l esAppl et . cl ass" WI DTH=300 HEI GHT=200>

*************** End of Lecture 11a **************

UIU Lecture 11a, CSI 211
1/7
United International University

Course: CSI 211
Course Title: Object Oriented Programming
Lecture 11b: Applet


Applet
The HTML : HelloApplet.html

<HTML>
<HEAD>
<TI TLE>Hel l oAppl et </ TI TLE>
</ HEAD>
<BODY>
<HR>
Thi s i s t he f i r st Appl et <P>
<APPLET
code=" Hel l oAppl et . cl ass" wi dt h=100 hei ght =100>
</ APPLET><BR>
The End
<HR>
</ BODY>
</ HTML>


The Java Code: HelloApplet.java
i mpor t j ava. awt . *;
i mpor t j ava. appl et . Appl et ;
publ i c cl ass Hel l oAppl et ext ends Appl et
{
publ i c voi d i ni t ( ) {
r epai nt ( ) ;
}

publ i c voi d pai nt ( Gr aphi cs g ) {
g. dr awSt r i ng( " Hel l o Wor l d! " , 30, 30 ) ;
}
}


Command line-
C:\>appletviewer HellloApplet.html

UIU Lecture 11a, CSI 211
2/7
Output
Note: all examples are done using the applet viewer




Applet Methods

init()
Called by the browser or applet viewer when an applet is loaded into the system. This is
used to replace the functionality of constructor. This method is called only once in the life
of an applet object.

start()
Called by the browser or applet viewer to inform an applet that it should start its
execution. It is called automatically after the init() method is called. It is also called when
the user returns to the page containing the applet, after viewing other pages. Start is often
used to start threads and animation. This method can be called more than once in the life
of an applet object.

stop()
Called by the browser or applet viewer to inform an applet that it should stop its
execution. This is called when the user moves off to another page. Use this to stop
animations, threads, and playing audio files. If you do not use animation, threads or audio
files you normally don't need to implement stop().. This method can be called more than
once in the life of an applet object.



UIU Lecture 11a, CSI 211
3/7
destroy()
Called by the browser or applet viewer to inform this applet that it is being unloaded. Use
this method to reclaim any non-memory-dependent destroy resources that it has allocated
(like graphics contexts). This method is called only once in the life of an applet object.

Example

This example just displays when the basic applet methods are run in an applet. The output
is displayed in a TextArea. In order to save space on the slide, I will only display the
applet part of the HTML. This does work with the applet viewer and broswers, although
it is not proper HTML.

HTML
<APPLET
CODE=" Basi cEvent Appl et . cl ass" WI DTH=300 HEI GHT=200>
</ APPLET>

Java Code
i mpor t j ava. awt . *;
i mpor t j ava. appl et . Appl et ;
publ i c cl ass Basi cEvent Appl et ext ends Appl et
{
Text Ar ea messages = new Text Ar ea( 8, 30) ;

publ i c Basi cEvent Appl et ( ) {
messages. append( " Const r uct or \ n" ) ;
}

publ i c voi d i ni t ( ) {
add( messages ) ;
messages. append( " I ni t \ n" ) ;
}

publ i c voi d st ar t ( ) { messages. append( " St ar t \ n" ) ; }
publ i c voi d st op( ) { messages. append( " St op\ n" ) ; }
publ i c voi d dest r oy( ) { messages. append( " Dest r oy\ n" ) ; }

publ i c voi d pai nt ( Gr aphi cs g ) {messages. append( " Pai nt \ n" ) ; }
}



Output
Note: all examples are done using the applet viewer

UIU Lecture 11a, CSI 211
4/7




Alternative Text

Some browsers do not support applets. You should provide alternative text to be
displayed in such browsers. The tag below provides such text.
<APPLET
CODE=" Basi cEvent Appl et . cl ass" WI DTH=300 HEI GHT=200>
Your br owser does <B>not </ B> suppor t appl et s! So you can
not use my gr eat appl et .
</ APPLET>


Applet Parameters
This example shows how to pass information to an applet from the html page. The
getParameter() method will read arguments with the param tag. It also seems to read the
width & height. The methods getAppletInfo() & getParameterInfo() are used by the
applet viewer to provide the user with information about the applet.

HTML
<APPLET
CODE=" Par amet er Appl et . cl ass" WI DTH=300 HEI GHT=200>
<PARAM NAME=" name" VALUE=" Roger " >
<PARAM NAME=" your Hei ght " VALUE=" 5" >
</ APPLET>

UIU Lecture 11a, CSI 211
5/7
Java Code
i mpor t j ava. awt . *;
i mpor t j ava. appl et . Appl et ;
publ i c cl ass Par amet er Appl et ext ends Appl et {
Text Ar ea messages = new Text Ar ea( 8, 20) ;

publ i c voi d i ni t ( ) {
add( messages ) ;
St r i ng name = get Par amet er ( " name" ) ;
i nt hei ght =
I nt eger . val ueOf ( get Par amet er ( " your Hei ght " ) ) . i nt Val ue( ) ;
messages. append( " name: " + name + " \ n" ) ;
messages. append( " hei ght : " + hei ght + " \ n" ) ; }
publ i c St r i ng get Appl et I nf o( ) {
r et ur n " Thi s appl et shows how t o pass i nf or mat i on" +
" f r omt he ht ml document t o t he appl et " ; }

publ i c St r i ng[ ] [ ] get Par amet er I nf o( ) {
r et ur n new St r i ng[ ] [ ] {
{ " name" , " st r i ng" , " your name" },
{ " your Hei ght " , " i nt " , " your hei ght " }
};
}
}


Output
Note: all examples are done using the applet viewer




Multiple Files
An applet may require more than one .class file, or it may require a sound file or image
files. By default, all files are loaded from the same location as the .html file that refers to
the applet. In the following example, the applet requires the file AnotherClass.class to

UIU Lecture 11a, CSI 211
6/7
run. It is downloaded from the same location as the .html file and the
MultipleFilesApplet.class file.

HTML
<APPLET
CODE=" Mul t i pl eFi l esAppl et . cl ass" WI DTH=300 HEI GHT=200>
</ APPLET>

Java Code
i mpor t j ava. awt . *;
i mpor t j ava. appl et . Appl et ;
publ i c cl ass Mul t i pl eFi l esAppl et ext ends Appl et
{
publ i c voi d i ni t ( ) {
r epai nt ( ) ;
}
publ i c voi d pai nt ( Gr aphi cs di spl ay ) {
Anot her Cl ass t est = new Anot her Cl ass( ) ;
di spl ay. dr awSt r i ng( t est . name( ) , 20, 20 ) ;
}
}
publ i c cl ass Anot her Cl ass {
publ i c St r i ng name( ) {
r et ur n " Roger " ;
}
}

JAR Files
The files required by an applet can be placed into a jar file. A jar file is a compressed file
(zip algorithm) with a manifest (list of contents). This can speed up the transfer of the
applet in two ways. First, the file is compressed. Second, if requires only one interaction
with the web server to obtain all the needed files. The example below, shows how create
and access a jar file for the applet .

The basic syntax for creating a jar file is:
j ar - cf j ar Fi l eName. j ar f i l e1, f i l e2, . . . , f i l eN

where file1, ..., fileN are the files to put into the jar file.

The following command creates the file myJ ar.jar for the example on the previous slide.

UIU Lecture 11a, CSI 211
7/7

j ar - cf myJ ar . j ar Anot her Cl ass. cl ass Mul t i pl eFi l esAppl et . cl ass

The following applet tag tells the browser/appleviewer to also look into the jar file
myjar.jar to find any files needed by the applet. The jar file will be loaded from the same
location as the html file. You can specify more than one jar file by separating the file
names with commas: archive="jar1.jar, jar2.jar".
<APPLET
ARCHI VE=" myJ ar . j ar "
CODE=" Mul t i pl eFi l esAppl et . cl ass" WI DTH=300 HEI GHT=200>

*************** End of Lecture 11a **************

UIU Lecture 12a, CSI 211
1/3
United International University

Course: CSI 211
Course Title: Object Oriented Programming
Lecture 12a: Applet-2


Size of Applet Area

This example shows how to determine the applet's size.

HTML
<APPLET ar chi ve=" Appl et Cl asses. j ar "
code=" Si zeAppl et . cl ass" wi dt h=100 hei ght =100>
</ APPLET>

Java Code
i mpor t j ava. awt . *;
i mpor t j ava. appl et . Appl et ;
publ i c cl ass Si zeAppl et ext ends Appl et
{
publ i c voi d i ni t ( ) {
r epai nt ( ) ;
}

publ i c voi d pai nt ( Gr aphi cs di spl ay ) {
Di mensi on si ze = get Si ze( ) ;
di spl ay. dr awSt r i ng( " hei ght = " + si ze. hei ght , 30, 30 ) ;
di spl ay. dr awSt r i ng( " wi dt h = " + si ze. wi dt h, 30, 50 ) ;
di spl ay. dr awRect ( 0, 0, si ze. wi dt h- 1, si ze. hei ght - 1) ;
}
}

Output
Note: all examples are done using the applet viewer







UIU Lecture 12a, CSI 211
2/3
CodeBase
Use the codebase tag to specify a location to find the files needed by the applet. You can
specify the location relative to the location of the referencing .html file (document base)
or give a full URL.
Specify Full URL
Look for the .class files in the specified location
<APPLET
CODEBASE= " ht t p: / / www. el i . sdsu. edu/ cour ses/ f al l 98/ cs596/ not es/ code"
CODE=" Mul t i pl eFi l esAppl et . cl ass" WI DTH=300 HEI GHT=200>
</ APPLET>



Status Window

Some browsers have a "status window".
The showStatus() method places text in that window.

i mpor t j ava. awt . *;
i mpor t j ava. appl et . Appl et ;
publ i c cl ass St at usAppl et ext ends Appl et
{
publ i c voi d pai nt ( Gr aphi cs di spl ay) {
showSt at us( " Hi mom" ) ;
}
}


Applets & AWT
An Applet is a subclass of Container and Panel. FlowLayout is the default layout
manager for applets. We can add any AWT component to an applet we can add to a
Panel. The example below shows adding buttons to an applet.

HTML
<APPLET ar chi ve=" Appl et Cl asses. j ar "
code=" But t onAppl et . cl ass" wi dt h=100 hei ght =100>
<par amname=" name" val ue=" Roger " >
</ APPLET>


UIU Lecture 12a, CSI 211
3/3
Java Code
i mpor t j ava. awt . *;
i mpor t j ava. appl et . Appl et ;
i mpor t j ava. awt . event . *;
publ i c cl ass But t onAppl et ext ends Appl et {
But t on r ed = new But t on( " Red" ) ;
But t on bl ue = new But t on( " Bl ue" ) ;

publ i c voi d i ni t ( ) {
add( r ed ) ;
add( bl ue ) ;
r ed. addAct i onLi st ener ( new Col or Act i onLi st ener ( Col or . r ed) ) ;
bl ue. addAct i onLi st ener ( new Col or Act i onLi st ener ( Col or . bl ue) ) ;
}
cl ass Col or Act i onLi st ener i mpl ement s Act i onLi st ener {
Col or backgr oundCol or ;

publ i c Col or Act i onLi st ener ( Col or aCol or ) {
backgr oundCol or = aCol or ;
}
publ i c voi d act i onPer f or med( Act i onEvent event ) {
set Backgr ound( backgr oundCol or ) ;
r epai nt ( ) ;
}
}
}


Output
Note: all examples are done using the applet viewer




*************** End of Lecture 12a **************

UIU Lecture 12b, CSI 211
1/5
United International University

Course: CSI 211
Course Title: Object Oriented Programming
Lecture 12b: Applet-3



Tables - Swing

import java.awt.*;
import javax.swing.*;
/*
<applet code="JTableDemo" width=400 height=200>
</applet>
*/


public class JTableDemo extends JApplet {

public void init() {
// Get content pane
Container contentPane = getContentPane();
// Set layout manager
contentPane.setLayout(new BorderLayout());
// Initialize column headings
final String[] colHeads = { "Name", "Phone", "Fax" };
// Initialize data
final Object[][] data = {
{ "Gail", "4567", "8675" },
{ "Ken", "7566", "5555" },
{ "Viviane", "5634", "5887" },
{ "Melanie", "7345", "9222" },
{ "Anne", "1237", "3333" },
{ "John", "5656", "3144" },
{ "Matt", "5672", "2176" },
{ "Claire", "6741", "4244" },
{ "Erwin", "9023", "5159" },
{ "Ellen", "1134", "5332" },
{ "Jennifer", "5689", "1212" },
{ "Ed", "9030", "1313" },
{ "Helen", "6751", "1415" }
};
// Create the table
JTable table = new JTable(data, colHeads);
// Add table to a scroll pane
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(table, v, h);
// Add scroll pane to the content pane
contentPane.add(jsp, BorderLayout.CENTER);
}
}


UIU Lecture 12b, CSI 211
2/5




Trees
A tree is a component that presents a hierarchical view of data. A user has the ability to expand or
collapse individual subtrees in this display. Trees are implemented in Swing by the JTree class,
which extends JComponent.


/*
<applet code="JTreeEvents" width=400 height=200>
</applet>
*/

public class JTreeEvents extends JApplet {
JTree tree;
JTextField jtf;
public void init() {
// Get content pane
Container contentPane = getContentPane();
// Set layout manager
contentPane.setLayout(new BorderLayout());
// Create top node of tree
DefaultMutableTreeNode top = new
DefaultMutableTreeNode("Options");
// Create subtree of "A"
DefaultMutableTreeNode a = new DefaultMutableTreeNode("A");
top.add(a);
DefaultMutableTreeNode a1 = new
DefaultMutableTreeNode("A1");
a.add(a1);
DefaultMutableTreeNode a2 = new
DefaultMutableTreeNode("A2");
a.add(a2);
// Create subtree of "B"
DefaultMutableTreeNode b = new DefaultMutableTreeNode("B");
top.add(b);
DefaultMutableTreeNode b1 = new
DefaultMutableTreeNode("B1");

UIU Lecture 12b, CSI 211
3/5
b.add(b1);
DefaultMutableTreeNode b2 = new
DefaultMutableTreeNode("B2");
b.add(b2);
DefaultMutableTreeNode b3 = new
DefaultMutableTreeNode("B3");
b.add(b3);
// Create tree
tree = new JTree(top);
// Add tree to a scroll pane
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(tree, v, h);
// Add scroll pane to the content pane
contentPane.add(jsp, BorderLayout.CENTER);
// Add text field to applet
jtf = new JTextField("", 20);
contentPane.add(jtf, BorderLayout.SOUTH);
// Anonymous inner class to handle mouse clicks
tree.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
doMouseClicked(me);
}
}
)

void doMouseClicked(MouseEvent me) {
TreePath tp = tree.getPathForLocation(me.getX(), me.getY());
if(tp != null)
jtf.setText(tp.toString());
else
jtf.setText("");
}
}









Wat ch. ht ml

4/5

1: <ht ml >
2: <head>
3: <t i t l e>Wat ch Appl et </ t i t l e>
4: </ head>
5: <body>
6: <appl et code=" Wat ch. cl ass" hei ght =" 50" wi dt h=" 345" >
7: Thi s pr ogr amr equi r es a J ava- enabl ed br owser .
8: </ appl et >
9: </ body>
10: </ ht ml >






Watch.java
1: i mpor t j ava. awt . *;
2: i mpor t j ava. ut i l . *;
3:
4: publ i c cl ass Wat ch ext ends j avax. swi ng. J Appl et {
5: pr i vat e Col or but t er scot ch = new Col or ( 255, 204, 102) ;
6: pr i vat e St r i ng l ast Ti me = " " ;
7:
8: publ i c voi d i ni t ( ) {
9: set Backgr ound( Col or . bl ack) ;
10: }
11:
12: publ i c voi d pai nt ( Gr aphi cs scr een) {
13: Gr aphi cs2D scr een2D = ( Gr aphi cs2D) scr een;
14: Font t ype = new Font ( " Monospaced" , Font . BOLD, 20) ;
15: scr een2D. set Font ( t ype) ;
16: Gr egor i anCal endar day = new Gr egor i anCal endar ( ) ;
17: St r i ng t i me = day. get Ti me( ) . t oSt r i ng( ) ;
18: scr een2D. set Col or ( Col or . bl ack) ;
19: scr een2D. dr awSt r i ng( l ast Ti me, 5, 25) ;
20: scr een2D. set Col or ( but t er scot ch) ;
21: scr een2D. dr awSt r i ng( t i me, 5, 25) ;
22: t r y {
23: Thr ead. sl eep( 1000) ;
5/5
24: } cat ch ( I nt er r upt edExcept i on e) {
25: / / do not hi ng
26: }
27: l ast Ti me = t i me;
28: r epai nt ( ) ;
29: }
30: }



*************** End of Lecture 12b **************

1/4


Separating the GUI from the Program

Problem 1
Create a simple counter that can:
Increase
Decrease
Be reset to zero

Display the counter in a window and allow the user to increase or decrease the counter
via buttons.


A Poor Solution - The Window is the Counter

cl ass BadCount er Exampl e ext ends Fr ame {
But t on i ncr ease = new But t on( " I ncr ease" ) ;
But t on decr ease = new But t on( " Decr ease" ) ;
But t on r eset = new But t on( " Reset " ) ;
i nt count = 0;

publ i c BadCount er Exampl e( i nt wi dt h, i nt hei ght ) {
set Ti t l e( " Bad Count er Exampl e" ) ;
set Si ze( wi dt h, hei ght ) ;
set Layout ( new Fl owLayout ( ) ) ;
add( i ncr ease ) ;
add( decr ease ) ;
add( r eset ) ;

i ncr ease. addAct i onLi st ener ( new I ncr easeLi st ener ( ) ) ;
decr ease. addAct i onLi st ener ( new Decr easeLi st ener ( ) ) ;
r eset . addAct i onLi st ener ( new Reset Li st ener ( ) ) ;
show( ) ;
}
publ i c voi d pai nt ( Gr aphi cs di spl ay ) {
di spl ay. dr awSt r i ng( " The count i s " + count , 50, 50 ) ;
}
publ i c st at i c voi d mai n( St r i ng ar gs[ ] ) {
new BadCount er Exampl e( 200, 100 ) ;
}
cl ass I ncr easeLi st ener i mpl ement s Act i onLi st ener {
2/4
publ i c voi d act i onPer f or med( Act i onEvent event ) {
count ++;
r epai nt ( ) ;
}
}
cl ass Decr easeLi st ener i mpl ement s Act i onLi st ener {
publ i c voi d act i onPer f or med( Act i onEvent event ) {
count - - ;
r epai nt ( ) ;
}
}
cl ass Reset Li st ener i mpl ement s Act i onLi st ener {
publ i c voi d act i onPer f or med( Act i onEvent event ) {
count = 0;
r epai nt ( ) ;
}
}
}



Output After clicking on Increase 6 times




What is Wrong with the about program? It works!

What happens if we need to run the program in batch mode? There is no way to separate
the code from window environment!


Model-View

A Model is a system of objects that perform a task
A View: Displays a representation of the model by asking model for values to
display. It handles all interaction with user about the model . Keeping the model
and view separate
3/4

o Give flexibility in combining new views to a model
o Allows multiple views on the same model





Counter Model

We use a separate class to implement the counter model. Of course, normally the model
is more complex than the counter. Hence, it may require a lot more that one class to
implement.

cl ass Count er {
pr i vat e i nt count = 0;

publ i c voi d i ncr ease( ) {
count ++;
}
publ i c voi d decr ease( ) {
count - - ;
}
publ i c voi d r eset ( ) {
count = 0;
}

publ i c i nt val ue( ) {
r et ur n count ;
}
publ i c St r i ng t oSt r i ng( ) {
r et ur n St r i ng. val ueOf ( count ) ;
}
}



A View for the Model

i mpor t j ava. awt . *;
i mpor t j ava. awt . event . Act i onLi st ener ;
i mpor t j ava. awt . event . Act i onEvent ;
cl ass Count er Exampl e ext ends Fr ame {
But t on i ncr ease = new But t on( " I ncr ease" ) ;
But t on decr ease = new But t on( " Decr ease" ) ;
But t on r eset = new But t on( " Reset " ) ;
4/4
Count er count ;

publ i c Count er Exampl e( i nt wi dt h, i nt hei ght , Count er out si de ) {
set Ti t l e( " Model - Vi ew Exampl e" ) ;
set Si ze( wi dt h, hei ght ) ;
set Layout ( new Fl owLayout ( ) ) ;
add( i ncr ease ) ;
add( decr ease ) ;
add( r eset ) ;
count = out si de;
i ncr ease. addAct i onLi st ener ( new I ncr easeLi st ener ( ) ) ;
decr ease. addAct i onLi st ener ( new Decr easeLi st ener ( ) ) ;
r eset . addAct i onLi st ener ( new Reset Li st ener ( ) ) ;
show( ) ;
}
publ i c voi d pai nt ( Gr aphi cs di spl ay ) {
di spl ay. dr awSt r i ng( " The count i s " + count , 50, 50 ) ;
}
cl ass I ncr easeLi st ener i mpl ement s Act i onLi st ener {
publ i c voi d act i onPer f or med( Act i onEvent event ) {
count . i ncr ease( ) ;
r epai nt ( ) ;
}
}
cl ass Decr easeLi st ener i mpl ement s Act i onLi st ener {
publ i c voi d act i onPer f or med( Act i onEvent event ) {
count . decr ease( ) ;
r epai nt ( ) ;
}
}
cl ass Reset Li st ener i mpl ement s Act i onLi st ener {
publ i c voi d act i onPer f or med( Act i onEvent event ) {
count . r eset ( ) ;
r epai nt ( ) ;
}
}
}


*************** End of Lecture 13a **************

You might also like