Learn Java in 30 Days Free
Learn Java in 30 Days Free
}
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 **************