M251 - Meetings 3-4-5-7-8-9-10-11-13&14

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 445

M251 Meeting 3:

Objects and Classes

Edited by: Dr. Bayan Abu Shawar


AOU-Jordan

1
Objectives

 To describe, declare, create objects and classes.

 To create objects using constructors.

 To access objects via reference variables.

 To distinguish between instance and static variables and methods.

 Visibility Modifiers

 To define private data fields with appropriate get and set methods.

2
O.O. Programming Concepts
Object-oriented programming (OOP) involves programming
using objects.
An object represents an entity in the real world that can be
distinctly identified. An object is an instance of a class.
For example, a student, a desk, a circle, a button, and even a
loan can all be viewed as objects. An object has a unique
identity, state, and behaviors.
The state of an object consists of a set of data fields (also
known as properties, attributes) with their current values.
The behavior of an object is defined by a set of methods.

3
Objects

Class Name: Circle A class template

Data Fields:
radius is _______

Methods:
getArea

Circle Object 1 Circle Object 2 Circle Object 3 Three objects of


the Circle class
Data Fields: Data Fields: Data Fields:
radius is 10 radius is 25 radius is 125

An object has both a state and behavior. The state


defines the object (current values of its attributes), and
the behavior defines what the object does.
4
Classes

Classes are constructs that define objects of the same


type. A class is used to group related objects together. A
class is considered as a factory to create objects.
A Java class uses variables (attributes) to define data
fields and methods to define behaviors.
Additionally, a class provides a special type of
methods, known as constructors, which are invoked to
construct objects from the class.

5
An Example of Classes
class Circle {
/** The radius of this circle */
double radius = 1.0; Data field

/** Zero-argument-Construct */
Circle() {
}
Constructors
/** One-argument Construct */
Circle(double newRadius) {
radius = newRadius;
}

/** Return the area of this circle */


double getArea() { Method
return radius * radius * 3.14159;
}
}//end of a class
6
UML Class Diagram
UML Class Circle Class name
Unified
Diagram
radius: double
Data fields
Modeling
Language
Circle()
Constructors and (UML): is a
Circle(newRadius: double) methods standard
getArea(): double
UML modeling
getPerimeter(): double language,
notation
for objects setRadius(newRadius: double): which is
void
based on
diagrams and
their
circle1: Circle circle2: Circle circle3: Circle construction
, meaning
radius = 1.0 radius = 25 radius = 125 and use.
7
Example: Defining Classes and Creating Objects
Objective: Demonstrate creating objects, accessing data, and
using methods.
public class TestCircle {
public static void main(String[] args) {
// Create a circle with radius 1 TestSimpleCircle
Circle circle1 = new Circle();
System.out.println("The area of the circle of radius "
+ circle1.radius + " is " + circle1.getArea()); Run
 
// Create a circle with radius 25
Circle circle2 = new Circle(25);
System.out.println("The area of the circle of radius "+ circle2.radius +" is”
+ circle2.getArea());
  // Create a circle with radius 125
Circle circle3 = new Circle(125);
System.out.println("The area of the circle of radius "
+ circle3.radius + " is " + circle3.getArea());
 
// Modify circle radius
circle2.radius = 100; // or circle2.setRadius(100)
System.out.println("The area of the circle of radius "
+ circle2.radius + " is " + circle2.getArea());
}
}//end of class 8
Constructors
Constructors are a special kind of methods that are
invoked to initialise objects.
//Zero-argument constructor
Circle() {
}

//One-argument constructor
Circle(double newRadius) {
radius = newRadius;
}

9
.Constructors, cont

A constructor with no parameters is referred to as a


no-arg or zero-arg constructor.
Constructors must have the same name as the class
itself.
Constructors do not have a return type—not even
void.
Constructors are invoked using the new operator
when an object is created. Constructors play the role of
initializing objects.
10
Default Constructor

A class may be defined without constructors. In


this case, a no-arg constructor with an empty body
is implicitly defined in the class.
This constructor, called a default constructor, is
provided automatically only if no constructors are
explicitly defined in the class.

11
Declaring Object Reference
Variables

To declare an object (reference variable), use


the syntax:
ClassName objectRefVarName;
Example:
Circle myCircle;
To create an object:
objectName = ClassName;
mycircle = new Circle();
12
Declaring/Creating Objects
in a Single Step
ClassName objectRefVar = new ClassName();
 Example:
Assign object reference Create an object

Circle myCircle = new Circle();

Invoking constructor
Data_Type Object_name Create a new
memory to initialize the
location for the created object
object
13
Accessing Class Members

There are two ways to access the class members:


(1) Using a qualified name with an object reference and a dot notation,
for example: objectRefVar.methodName(arguments)
e.g., myCircle.getArea();

(2) Using a simple name a name without a reference and dot notation,
e.g., getArea(); or radius = 1;

When to use them?


Simple name:
• Class members could be accessed using the simple name within their class.
• If we say a member is inherited we mean that the subclass has the same access to it
as if it were defined in the subclass.
Qualified name:
Other classes would have to have to use a qualified name.

•14
animation

Trace Code Declare myCircle

;Circle myCircle = new Circle(5.0) no value


myCircle
;)(Circle yourCircle = new Circle

;yourCircle.radius = 100

15
animation

.Trace Code, cont

;Circle myCircle = new Circle(5.0) no value


myCircle
;)(Circle yourCircle = new Circle
: Circle
;yourCircle.radius = 100 radius: 5.0

Create a
circle

16
animation

.Trace Code, cont

;Circle myCircle = new Circle(5.0)


myCircle reference value
;)(Circle yourCircle = new Circle

;yourCircle.radius = 100
: Circle

radius: 5.0
Assign object
reference to myCircle

17
animation

Trace Code, cont.


myCircle reference value
Circle myCircle = new Circle(5.0);

Circle yourCircle = new Circle();


: Circle
yourCircle.radius = 100;
radius: 5.0

yourCircle no value

Declare yourCircle

18
animation

Trace Code, cont.


myCircle reference value
Circle myCircle = new Circle(5.0);
: Circle
Circle yourCircle = new Circle();
radius: 5.0

yourCircle.radius = 100;

yourCircle no value

: Circle
Create a new
radius: 1.0
Circle object

19
animation

.Trace Code, cont


reference value
Circle myCircle = new Circle(5.0); myCircle

Circle yourCircle = new Circle(); : Circle

radius: 5.0
yourCircle.radius = 100;

yourCircle reference value

Assign object
reference to : Circle
yourCircle
radius: 1.0

20
animation

Trace Code, cont.


myCircle reference value
Circle myCircle = new Circle(5.0);
: Circle
Circle yourCircle = new Circle();
radius: 5.0
yourCircle.radius = 100;

yourCircle reference value

: Circle
Change radius in
yourCircle radius: 100.0

21
Caution

Recall that you use


Math.methodName(arguments) (e.g., Math.pow(3, 2.5))

to invoke a method in the Math class. Can you invoke


getArea() using SimpleCircle.getArea()? The answer is no.

All the methods used before in M105 module were static


methods, which are defined using the static keyword.
However, getArea() is non-static. It must be invoked from
an object using
objectRefVar.methodName(arguments) (e.g.,
myCircle.getArea()).

22
Data fields (Attributes)
The data fields can be of primitive types as any
other variables or reference types.

For example, the following Student class contains


a data field name of the String type.
public class Student {

String name; // name has default value null

int age; // age has default value 0

boolean isScienceMajor; // isScienceMajor has default value false

char gender; // c has default value '\u0000'


}

23
The null Value

If a data field of a reference type does


not reference any object, the data field
holds a special literal value, null.

24
Default Value for a Data Field

The default value of a data field is:


null for a reference type,

0 for a numeric type,

false for a boolean type,

and '\u0000' for a char type.

However, Java assigns no default value to a local


variable inside a method.
25
Creating Objects from student Class

public class Test {

public static void main(String[] args) {

Student student = new Student();

System.out.println("name? " + student.name);

System.out.println("age? " + student.age);

System.out.println("isScienceMajor? " + student.isScienceMajor);

System.out.println("gender? " + student.gender);


}

}// End of class

26
Example
Java assigns default values for attributes (by
default constructor), but NO default valuee
to local variables inside a method.
public class Test {

public static void main(String[] args) {

int x; // x has no default value

String y; // y has no default value

System.out.println("x is " + x);

System.out.println("y is " + y);


Compile error: variable not initialized
}

} 27
Differences between Variables of
Primitive Data Types and Object (Reference) Types

Created using new Circle()


Primitive type int i = 1 i 1

Object type Circle c c reference c: Circle

radius = 1

28
Copying Variables of Primitive Data
Types and Object (reference) Types
Primitive type assignment: i = j Object type assignment: c1 = c2

Before: Before: After:


After:

i 1 i 2 c1 c2 c1
c2
j 2 j 2

c1: Circle c2: Circle c1: Circle c2: Circle


radius = 5 radius = 9 radius = 5 radius = 9

29
Garbage Collection

As shown in the previous figure, after


the assignment statement c1 = c2, c1
points to the same object referenced by
c2. The object previously referenced by
c1 is no longer referenced. This object
is known as garbage. Garbage is
automatically collected by (java Virtual
Machine (JVM).
30
Garbage Collection, cont

TIP: If you know that an object is no longer


needed, you can explicitly assign null to a
reference variable for the object. The JVM
will automatically collect the space if the
object is not referenced by any variable.

31
Data fields and Methods
Data fields can be classified into:

Instance variables and static variables

Methods can be classified into:

Instance methods and static methods

32
Instance Variables and Instance
Methods
Instance variables belong to a specific
instance (object). For example:
Circle myCircle = new Circle(5.0);
myCircle : Circle

radius: 5.0

Instance methods are invoked by an


instance of the class. For example:
double x = myCircle.getArea();
Static Variables, Constants,
and Methods
Static variables (class variables) are shared by all the instances of the class.
Class variables are used to keep count of the number of objects of a class
type that have been created. As each object would have to update the count
every time a new object came into existence – (in the constructors).
Static methods (class methods) are not tied to a specific object.
You could not access an instance member from a class method.

Static constants are final variables shared by all the instances of the class,

and usually intiaised upon declaration.

You can access class variables and methods using class name.
34
Static Variable Example
Public class VariableDemo {
static int count=0;

public void increment() { count++; }

public static void main(String args[]) {


VariableDemo obj1=new VariableDemo();
VariableDemo obj2=new VariableDemo();
obj1.increment();
obj2.increment();
System.out.println("Obj1: count is="+obj1.count);
System.out.println("Obj2: count is="+obj2.count);
}
}
Output:
Obj1: count is=2 Obj2: count is=2
35
Static Constants
To declare static variables, constants, and
methods, use the static modifier.
For example: PI is declared inside Math class as constant :

So you can access it using: Math.PI


• It is public because we wish it to be available to other classes,
• It is static because it has one value for all objects of the class
• It is final because pi is a constant.
• It is double because that is the most accurate decimal representation we
can use.

36
Scope of Variables

 The scope of instance and static variables is the


entire class. They can be declared anywhere
inside a class.
 The scope of a local variable starts from its
declaration and continues to the end of the block
that contains the variable. A local variable must
be initialized explicitly before it can be used.

37
Static methods (also known as a class methods) and
their uses

• Static
methods carry out general functions not associated with objects.
• Class Variable can be accessed directly in a class method, inan instance
method and in constructor.

– For example, the static method max within the class Math returns the greater
of its two arguments. The method header for one version of max looks like this:
public static double max (double a, double b)
{
if (a>b)
return a;
else
return b;
}
 To access it: double val = Math.max(Math.PI, 4.0);
 The main method is a static method.
38
Static Variables, Constants,
.and Methods, cont

39
Packages
 A package is used to associate a number of classes that are closely
related to one another.
– if classes form a cohesive group, they should be marked as belonging to the same
package.
– For example, Java has a collection of classes named java.math.
– If we wanted to make use of this package, we would add a statement to
advise the Java system of this, by adding an import statement at the
beginning of our program. In this case we would say:

The .* notation means 'all the classes in the package.

40
Access modifiers
There are three keywords associated with controlling levels of access to class members
in Java: public, protected & private. These are known as access modifiers.

There is actually a fourth level of access, 'default'. There is no 'default‘ keyword;


default access arises when none of the access modifiers is specified.

The following example illustrates the accessibility:

Example:

Visibility for a ref. var. defined in Alpha

41
Visibility Modifiers and
Accessor/Mutator Methods
By default, the class, variable, or method can be
accessed by any class in the same package.
 public
The class, data, or method is visible to any class in any package using
qualified name (a reference and a dot notation).
 private
The data or methods can be accessed only by the declaring class. The get and
set methods are used to read and modify private properties.
 Protected
The data or methods are accessible inside class where they are declared, and
inside subclasses. All class in the same package can access protected member
using qualified name.
 No modifier: default members can be accessed by all classes in the same
package using qualified name
42
The private modifier restricts access to within a class, the default modifier
restricts access to within a package, and the public modifier enables unrestricted
access.

43
The default modifier on a class restricts access to within a package, and the
public modifier enables unrestricted access.

44
NOTE

An object cannot access its private members, as shown in (b). It is OK,


however, if the object is declared in its own class, as shown in (a).

45
Why Data Fields Should Be private?
To protect data.

To make code easy to maintain.

To achieve encapsulation principle (declare


attributes as private and methods as public)
and information hiding which are of Object
Oriented programming features.

46
Getter and setter methods
Usually you need to declare a setter and a getter methods for each
instance variable.

A getter method (also called an 'accessor' method):


– It is used to access private attributes from outside the class where they
were declared.
– A getter method should not change the state of the object.

– All private attributes should have getter methods .

For example, inside the class Circle, we need to add another method:
public double getRadius(){
return radius}
In the main method: we invoke getRadius() using object name.
47
Setter Method

A setter method (also called a 'mutator'


method)
– It is one that changes the state of an object by setting the value of
an instance variable.
– Setter methods do not normally return a value.

For Example: Inside Circle class we need to add:

Public void setRadius(double r){


radius = r;
}
In the main method: we invoke setRadius() using object name.
48
Example of
Data Field Encapsulation
Circle
The - sign indicates
private modifier -radius: double The radius of this circle (default: 1.0).
-numberOfObjects: int The number of circle objects created.

+Circle() Constructs a default circle object.


+Circle(radius: double) Constructs a circle object with the specified radius.
+getRadius(): double Returns the radius of this circle.
+setRadius(radius: double): void Sets a new radius for this circle.
+getNumberOfObjects(): int Returns the number of circle objects created.
+getArea(): double Returns the area of this circle.

CircleWithPrivateDataFields

TestCircleWithPrivateDataFields Run
49
M251 Meeting 4:
Thinking in Objects and ArrayList
class
Edited by: Dr. Bayan Abu Shawar
AOU-Jordan

50
Objectives
Passing objects to methods 
Using this keyword 
Methods overloading 
Array of Objects 
.To apply Encapsulation and class abstraction 
ArrayList 
Stack and Queue Data Structures 

51
Passing Objects to Methods

Passing by value for primitive type value


(the value is passed to the parameter)
Passing by value for reference type value
(the value is the reference to the object)

TestPassObject Run

52
Passing Objects to methods example
{ public class TestPassObject
{ )(public static void main
;Circle c1 = new Circle(1)
.Print areas for radius 1, 2, 3, 4, and 5 //
;int n = 5
;printAreas(c1, n)
+ " System.out.println("\n" + "Radius is
;))(c1.getRadius
;System.out.println("n is " + n)
}
{ public static void printAreas( Circle a, int times)
;System.out.println("Radius \t\tArea")
{ while (times >= 1)
+ "System.out.println(a.getRadius() + "\t\t
;))(a.getArea
;a.setRadius(a.getRadius() + 1)
} ;--times
}
End Class //}

53
The keyword this

The this keyword is the name of a


reference that refers to an object itself.
One common use of the this keyword is
.reference a class’s hidden data fields
Another common use of the this keyword
to enable a constructor to invoke another
.constructor of the same class
54
Using this to refer to the Hidden Data
Fields
public class F { Suppose that f1 and f2 are two objects of F.
private int i = 5; F f1 = new F(); F f2 = new F();
private static double k = 0;
Invoking f1.setI(10) is to execute
void setI(int i) { this.i = 10, where this refers f1
this.i = i;
} Invoking f2.setI(45) is to execute
this.i = 45, where this refers f2
static void setK(double k) {
F.k = k;
}
}

55
Calling Overloaded Constructor

public class Circle {


private double radius;

public Circle(double radius) {


this.radius = radius;
} Instance variables-Attributes-
this must be explicitly used to reference the data
public Circle() { field radius of the object being constructed
this(1.0);
} this is used to invoke another constructor in the
same class
public double getArea() {
return this.radius * this.radius * Math.PI;
}
}
Every instance variable belongs to an instance represented by this,
which is normally omitted
56
The keyword this
.The word this can be used to invoke a constructor 
You can think of this as a reference to the class in which it 
.appears
:Consider the example on the right 

The first three constructors make use of 


the three-argument constructor. This is
a way of reusing constructors you have
written and can assist with readability
.when you have several constructors
Do not think of this(a, b, 0) as a call to 
a method. It is only possible to invoke
.constructors in this way
a constructor cannot invoke itself 
.(whereas a method can)

57
Array of Objects
;Circle[] circleArray = new Circle[10]
The above statement creates the array which can hold
.references to ten Circle objects
It doesn't create the circle objects themselves. They have to
be created separately using the constructor of the
 .Student class

:For example, if you try to write


;circleArray[0].setRadius(10)
This will produce a run time error since circleArray[0]
.points to null
58
.Array of Objects, cont

The Circle objects have to be instantiated using the constructor of the Circle
class and their references should be assigned to the array elements in the
following way. 
for(int i=0; i<circleArray.length; i++)
circleArray[i] = new circle();

//Invoking methods
double x = circleArray[0].getRadius();

59
Class Abstraction and Encapsulation
Class abstraction means to separate class implementation
.from the use of the class
The creator of the class provides a description of the class
.and let the user know how the class can be used
The user of the class does not need to know how the class
is implemented. The detail of implementation is encapsulated
.and hidden from the user

Class implementation Class Contract


is like a black box (Signatures of Clients use the
hidden from the clients
Class public methods and class through the
public constants) contract of the class

60
Object-Oriented Thinking
You studied before the fundamental
programming techniques for problem solving
.using loops, methods, and arrays
The studies of these techniques lay a solid
foundation for object-oriented programming. All
the previous code was written in the main
method so you could not re-use it in other
.projects
Classes provide more flexibility and
.modularity for building reusable software

61
Example: Defining Classes and Creating
Objects
TV
channel: int The current channel (1 to 120) of this TV.
volumeLevel: int The current volume level (1 to 7) of this TV.
on: boolean Indicates whether this TV is on/off.

The + sign indicates +TV() Constructs a default TV object.


a public modifier.
+turnOn(): void Turns on this TV.
+turnOff(): void Turns off this TV.
+setChannel(newChannel: int): void Sets a new channel for this TV.
+setVolume(newVolumeLevel: int): void Sets a new volume level for this TV.
+channelUp(): void Increases the channel number by 1.
+channelDown(): void Decreases the channel number by 1.
+volumeUp(): void Increases the volume level by 1.
+volumeDown(): void Decreases the volume level by 1.

62
Class TV
{ public class TV
public void setVolume(int
newVolumeLevel) { Attributes//
if (on && newVolumeLevel
int channel = 1; // Default channel >= is
1 &&
1
newVolumeLevel <= 7)
int volumeLevel = 1;volumeLevel
// Default =volume level is 1
newVolumeLevel;
boolean on} = false; // By default TV is off

public void channelDown() {


constructors //
if (on && channel > 1)
}{ )(public TV
channel--;
}
Methods//
{ )(public void
public void volumeUp() { turnOn
if (on && volumeLevel;on < 7)
= true
volumeLevel++;
}
}
{ )(public void turnOff
public void volumeDown() ;on {= false
if (on && volumeLevel > 1) }
volumeLevel--;
{ public void setChannel(int newChannel)
}
if (on && newChannel >= 1 && newChannel <= 120)
;channel = newChannel
}// end of class
}
{ )(public void channelUp
if (on && channel < 120)
TV TestTV Run
;++channel
}
Test TV class
public class TestTV {
public static void main() {
TV tv1 = new TV();
tv1.turnOn();
tv1.setChannel(30);
tv1.setVolume(3);

TV tv2 = new TV();


tv2.turnOn();
tv2.channelUp();
tv2.channelUp();
tv2.volumeUp();
System.out.println("tv1's channel is " + tv1.channel +
" and volume level is " + tv1.volumeLevel);
System.out.println("tv2's channel is " + tv2.channel +
" and volume level is " + tv2.volumeLevel);
}
64
}
ArrayList Class

You can create an array to store objects.


But the array’s size is fixed once the array
.is created
Java provides the ArrayList class that can
be used to store an unlimited number of
.objects
ArrayList Object

ArrayList is an indexable ordered 


collection of variable size that permits
.duplicate elements
Ordered collection means each element 
in the collection has a well-defined place,
.as indicated by its index number
ArrayList VS. Array

Objects of the generic class ArrayList are similar to


.arrays, but have differences

:Similarities
 Both can store a number of references (elements).

 The data can be accessed via an index.

 Elements duplication is allowed.


ArrayList Vs. Array
:Differences
ArrayList has no fixed size. You can extend the ArrayList as needed 
.automatically by adding elements
The ArrayList object requests more space from the Java run-time system, if 
.necessary
.The ArrayList is not ideal in its use of memory 
As soon as an ArrayList requires more space than its current capacity, the 
system will allocate more memory space for it. The extension is more than
required for the items about to be added. So there will often be empty
locations within an ArrayList – that is, the size will often be less than the
.capacity
:Two important terms in connection with ArrayList objects
The capacity of an ArrayList object is the maximum number of items it can currently 
.hold
.The size of an ArrayList object is the current number of items stored in the ArrayList 
The ArrayList Class
java.util.ArrayList<E>

+ArrayList() Creates an empty list.


+add(o: E) : void Appends a new element o at the end of this list.
+add(index: int, o: E) : void Adds a new element o at the specified index in this list.
+clear(): void Removes all the elements from this list.
+contains(o: Object): boolean Returns true if this list contains the element o.
+get(index: int) : E Returns the element from this list at the specified index.
+indexOf(o: Object) : int Returns the index of the first matching element in this list.
+isEmpty(): boolean Returns true if this list contains no elements.
+lastIndexOf(o: Object) : int Returns the index of the last matching element in this list.
+remove(o: Object): boolean Removes the first match of element o from this list.
+size(): int
Returns the number of elements in this list.
+remove(index: int) : E Removes the element at the specified index, and return it.
+set(index: int, o: E) : E Sets the element at the specified index.

69
Generic Type
ArrayList is known as a generic class with a generic
.>type E, e.g., ArrayList<E

You can specify a concrete type to replace E when


.creating an ArrayList

For example, the following statement creates an


ArrayList and assigns its reference to variable cities.
This ArrayList object can be used to store strings. We
.read it as ArrayList of String

ArrayList<String> cities = new ArrayList<String>();


TestArrayList Run
70
ArrayList Declaration and Creation
?How to declare an ArrayList
;)( >ArrayList <Object-Type> list1 = new ArrayList <Object-Type .1

;ArrayList <Object-Type> list1 = new ArrayList <Object-Type> (Capacity) .2

Note that : you need to use Wrapper Classes instead of primitive Data type
.inside the angle brackets <…> or any Object-Type

:Example 1
;)(>ArrayList <Integer> list2 = new ArrayList <Integer

This declaration of an ArrayList specifies that it will hold Integer references 


.The type “Integer” can be replaced by any object type 
. This declaration sets up an empty ArrayList 
The ArrayList capacity is expanded automatically as needed when items are added 
ArrayList Declaration and Creation
:Example 2

;ArrayList <Double> list1 = new ArrayList <Double> (100)

This declaration of an ArrayList specifies that it will hold Double references 


.The type “Double” can be replaced by any object type 
This declaration can be used to specify the initial capacity –in this case 100 
.elements
This can be more efficient in avoiding repeated work by the system in 
.extending the list, if you know approximately the required initial capacity
Exercise(1)

.Create a list to store cities called cityList .1


Add the following cities to cityList: London, Paris, Denver, Miami, .2
.Tokyo, Seoul
.Print out the list contents .3
.Print the size of the cityList .4
.Print out if Miami is in cityList .5
.Print out the location of Denver in the list .6
.Add another city Paris to the list in location 4 .7
.Remove the first occurrence of “Paris” from the list .8
// 1
ArrayList<String> cityList = new ArrayList<>();
// 2
cityList.add("London");
cityList.add("Denver");
cityList.add("Paris");
cityList.add("Miami");
cityList.add("Seoul");
cityList.add("Tokyo");
//3
System.out.println(cityList);
//4-6
System.out.println("List size? " + cityList.size());
System.out.println("Is Miami in the list? "+ cityList.contains("Miami"));
System.out.println("The location of Denver in the list? “+
cityList.indexOf("Denver"));
//7-8
cityList.add(4, "Paris");
cityList.remove ("Paris“);
Printing the ArrayList Object

There are 3 ways to print the ArrayList


:object
;System.out.println(cityList).1
:Using for loop as in the array.2
For(int i=0; i<cityList.size(); i++)
;System.out.prinltn(cityList.get(i))
Using for each statement .3

for(String x : cityList)
;system.out.println( x)

For each String X belong to cityList, x will


.hold the value itself not the index
The print statement could be replaced by
.other statement
Exercise(2)
.Create a list to store two circles .1
Add two circles .2
Display the area of the first circle in the list .3
:Solution
;)(>ArrayList<Circle> cl = new ArrayList<Circle
;cl.add(new Circle(5))
;cl.add(new Circle(2))
;System.out.println(“Radius of circle 1= “+ cl.get(0).getRadius())
;System.out.println("Area of circle 1 = "+ cl.get(0).getArea())
Differences and Similarities between
Arrays and ArrayList
Operation Array ArrayList

Creating an array/ArrayList String[] a = new String[10] ArrayList<String> list = new ArrayList<>();


Accessing an element a[index] list.get(index);
Updating an element a[index] = "London"; list.set(index, "London");
Returning size a.length list.size();
Adding a new element list.add("London");
Inserting a new element list.add(index, "London");
Removing an element list.remove(index);
Removing an element list.remove(Object);
Removing all elements list.clear();

DistinctNumbers Run

78
Array Lists from/to Arrays
It is also possible to create an equivalent list from a array
.list using the static method Arrays.asList(array)

:Example: Creating an ArrayList from an array of objects


;String[ ] array = {"red", "green", "blue"}
;ArrayList<String> list = new ArrayList<String>(Arrays.asList(array))

;System.out.println(list)

79
Creating an array of objects from
an ArrayList
It is possible to start with a List and create
an equivalent array containing the same
elements in the same order by using:
.toArray() method
String[ ] array1 = new String[list.size()];
list.toArray(array1);
Collections Utility Class

Collections class, is a treasure store of


class (static) methods for doing things to
collections, such as sorting or shuffling
them, picking out the largest or smallest
.item, and so on
Collections methods can be used with
.ArrayList object
;You need to import java.util.Collections
Methods of Collections Class
Methods of Collections Class
:Finding the maximum and minimum
The maximum or minimum element of a list 
can be found using the max() and min()
methods respectively. These methods
return the actual maximum and minimum
.values, not their positions
As with sorting, for this method to succeed, 
the elements must have a defined ordering,
.such as alphabetical or numerical
max and min in an Array List

;Integer[] array = {8,10,6,3,9}

;ArrayList<Integer> l1 = new ArrayList<Integer>(Arrays.asList(array))

;System.out.println(Collections.max(l1))

;System.out.println(Collections.min(l1))

84
Shuffling an Array List
The elements in a list can be put into
random order by passing the list as an
argument to the shuffle() method. For
,example
;Integer[] array = {3, 5, 95, 4, 15, 34, 3, 6, 5}

;ArrayList<Integer> list = new ArrayList<>(Arrays.asList(array))

;Collections.shuffle(list)
;System.out.println(list)

85
Exercise(3)
Create an array of Integer with values: .1
90,70,88,66,94,93
Create an Integer list name it list1 to have the .2
.same values as integer array
.Print the list1 .3
Print list1 in reverse order .4
Print out the maximum and minimum number in .5
list1
.Print out the summation of list1 .6
;Rearrange list1 in random order .7
Exercise(3)-Solution
1-2//
;Integer[] a1 = {90,70,88,66,94,93}
;ArrayList<Integer> list1 = new ArrayList<Integer>(Arrays.asList(a1))
3 //
;System.out.println(list1)
4//
;Collections.reverse(list1)
;System.out.println(list1)
5//
;System.out.println("Maximum is " + Collections.max(list1))
;System.out.println("Minimum is "+ Collections.min(list1))
6//
;double s =0
for(Integer y : list1)
;s = s+ y
;System.out.println(“List summation = "+ s)
7//
;Collections.shuffle(list1)
;System.out.println(list1)
Stack Data Structure

A Stack is a data structure that holds data 


.in a last-in-first-out order (LIFO)

:Main stack operations 


 push(object): inserts an element

 object pop(): removes and returns the last inserted element

88
Example

89
Designing the StackOfIntegers Class

Push()

Pop()

90
Stack Applications

Page-visited history in a Web browser


Undo sequence in a text editor
Chain of method calls in a language that
supports recursion.
The Stack could be implemented either as:
An Array,
ArrayList,
A Linked List

91
Stack Animation
https://liveexample.pearsoncmg.com/dsanimation/StackeBook.html

92
The MyStack Classes
Implement MyStack class as shown in class diagram
below. The stack will be represented as an ArrayList of
.Integers

MyStack
MyStack
-list: ArrayList A list to store elements.
+isEmpty(): boolean Returns true if this stack is empty.
+getSize(): int Returns the number of elements in this stack.
+peek(): Object Returns the top element in this stack.
+pop(): Object Returns and removes the top element in this stack.
+push(o: Object): void Adds a new element to the top of this stack.
+search(o: Object): int Returns the position of the first element in the stack from
the top that matches the specified element.

93
Class stack as an ArrayList
import java.util.ArrayList;

public class MyStack_ArrayList {

private ArrayList<Object> list = new ArrayList<>();

public boolean isEmpty() { return list.isEmpty(); }

public int getSize() { return list.size(); }

public void push(Object o) { list.add(o); } public Object pop() {


if(!(list.isEmpty())){
public Object peek() { Object o = list.remove(getSize() - 1);
if(!(list.isEmpty())) return o; }
return list.get(getSize() - 1); else
else return "The stack is empty";
return "The stack is empty"; }
}

public String toString() {


return "stack: " + list.toString();
}
}
Test_Stack Class
{public class Test_MyStack
{ public static void main(String[] args)
;)(Mystack_ArrayList y = new MyStack_ArrayList
;y.push(3)
;y.push(4)
;y.push(5)
;y.push(6)
;System.out.println("Number of elements in the stack are: "+y.getSize())

;System.out.println(y.pop())
;System.out.println(y.pop())

}
}
The Queue Data Structure

A Queue is a data structure that holds data


.in a first-in-first-out order (FIFO)
:Main Queue operations
void enqueue(object): inserts an element

object dequeue(): removes and returns the last inserted


element
Queue operations
:Auxiliary queue operations 
 object first(): returns the element at the front without
removing it

 integer len(): returns the number of elements stored

 boolean is_Empty(): indicates whether no elements are


stored
Example of Queue operations
Application of Queue

Waiting lists
Access to shared resources (e.g., printer)
Multiprogramming
Exercise (4)

Write a Java Class MyQueue to implement 


.the Queue operations

.You can implement Queue as an ArrayList 


MyQueue Class
import java.util.ArrayList;

public class MyQueue {


private ArrayList<Object> qlist= new ArrayList<Object>();

public boolean isEmpty() { return qlist.isEmpty(); }

public int len() { return qlist.size(); } public Object first() {


if(!(qlist.isEmpty()))
public void enqueue(Object o) {
return qlist.get(0);
qlist.add(o);
else
} return "The Queue is empty" ;

public String toString() { }


public Object dequeue() {
return “Queue: " + qlist.toString();
if(!(qlist.isEmpty())) {
} Object o = qlist.remove(0);
return o; }
else
return "The Queue is empty";
}
}//class
TestMyQueue
{ public class TestMyqueue

{ public static void main(String[] args)


;)(MyQueue q = new MyQueue
;q.enqueue(5)
;q.enqueue(10)
;q.enqueue(22)
;q.enqueue(53)
;System.out.println(q.first())
;System.out.println(q.dequeue())
;System.out.println(q.first())
;System.out.println(q.len())
;System.out.println(q.toString())
}
}
M251 Meeting 5:
Inheritance and Polymorphism

Edited by: Dr. Bayan Abu Shawar


AOU-Jordan

103
Motivations
Suppose you will define classes to model
circles, rectangles, and triangles. These
classes have many common features.
What is the best way to design these
classes so to avoid redundancy? The
.answer is to use inheritance

104
Objectives
 Relationships between classes
 Inheritance Relationship
 To define a subclass from a superclass.
 To invoke the superclass’s constructors and methods using the
super keyword.
 To override instance methods in the subclass.
 To distinguish differences between overriding and overloading.
 To explore the toString() method in the Object class.
 To explore the equals() method in the Object class.
 To discover polymorphism and dynamic binding.
 To describe casting and explain why explicit down casting is
necessary.

105
Inheritance Relationship between
classes
There are different types of relationships
:between
has-a relationship( classes
Composition
Aggregation
Inheritance is-a relationship(

In this lecture we will concentrate on the


inheritance relationship (is-a relationship) and
how to implement it in Java O.O. language.
Aggregation Relationships
Aggregations models has-a relationships and 
form a Whole-Part relationship between two
.classes
If you delete the Whole class (aggregating), the 
.Part one (Aggregated) will remain

Aggregating Aggregated
Class Class

107
Composition Relationships
. Composition is a stronger form of aggregation
,If the aggregating (composing) object is deleted

all of the aggregated (composed) objects must be


.deleted
Consider a Window object
containing a ScrollBar and a
Button. If the window is
destroyed, the scroll bar and
button must

108
Class Representation
An aggregation relationship is usually
represented as a data field in the aggregating
:class. follows
public class Name { public class Student { public class Address {
... private Name name; ...
} private Address address; }

...
}

Aggregated class Aggregating class Aggregated class

Composition Aggregation

1 1 1..3 1
Name Student Address 109
Aggregation or Composition

Since aggregation and composition


relationships are represented using
classes in similar ways, many texts don’t
differentiate them and call both
.compositions

110
Inheritance

Inheritance is an Object oriented feature 


which allows a class to inherit behavior
.(methods) and data from other class

With the use of inheritance the information 


is made manageable in a hierarchical
.order
Subclass and SuperClass
The class which inherits the properties of other 
is known as subclass (derived class, child
class). The subclass can have additional
.methods and data in addition to inherited ones

The class whose properties are inherited is 


known as superClass (base class, parent class).
Superclass holds the common data and
.methods
UML Notation for inheritance
What are the members of each class in the below class diagram?

SuperClass

Subclass

Subclass

Inheritance
UML notation
The Class Heirarchy
:There are two types in Java hierarchy 
1. user-defined
2. Java class library.

.The figure below shows a user-defined hierarchy 


class C and class D inheriting from class B which, in turn, inherits 
.from class A
Java inheritance hierarchy
The figure below shows part of the Java inheritance hierarchy,
including the root of the hierarchy, which is the class whose name is
.Object
.The class Object has no superclass
?Why Inheritance

The main benefit behind the inheritance is 


the reusability feature, where a new class
(subclass) can be created using an
existing one which save effort, time, avoid
.redundancy and reduce time of testing
Syntax of Java Inheritance

The extends keyword is used to represent 


.inheritance relationship in Java language

:The general format of subclass is 

public class Subclass-name extends Superclass-name  
{  
   //methods and fields  
}  
Superclasses and Subclasses
SimpleGeometricObject
-color: String The color of the object (default: white).
-filled: boolean Indicates whether the object is filled with a color (default: false).
-dateCreated: java.util.Date The date when the object was created.
+GeometricObject() Creates a GeometricObject.
+GeometricObject(color: String, Creates a GeometricObject with the specified color and filled
filled: boolean) values.
+getColor(): String
+setColor(color: String): void
Returns the color.
Sets a new color.
SimpleGeometricObject
+isFilled(): boolean Returns the filled property.
+setFilled(filled: boolean): void Sets a new filled property. Circle
+getDateCreated(): java.util.Date Returns the dateCreated.
+toString(): String Returns a string representation of this object.

Rectangle
Circle Rectangle
-radius: double -width: double
+Circle() -height: double TestCircleR
+Circle(radius: double) +Rectangle() ectangle
+Circle(radius: double, color: String, +Rectangle(width: double, height: double)
filled: boolean) +Rectangle(width: double, height: double
+getRadius(): double color: String, filled: boolean)
+setRadius(radius: double): void +getWidth(): double
+getArea(): double +setWidth(width: double): void Run
+getPerimeter(): double +getHeight(): double
+getDiameter(): double +setHeight(height: double): void
+printCircle(): void +getArea(): double
+getPerimeter(): double

118
Example: SimpleGeometricObject Class

import java.util.Date;
public class SimpleGeometricObject { public boolean isFilled()
private String color = "white"; { return filled; }
private boolean filled;
private Date dateCreated; public void setFilled(boolean
filled) { this.filled = filled;}
public SimpleGeometricObject() {
dateCreated = new java.util.Date(); public Date getDateCreated()
} {
public SimpleGeometricObject(String return dateCreated;
color, boolean filled) { }
dateCreated = new Date();
this.color = color; public String toString() {
this.filled = filled; return "created on " +
} dateCreated +
public String getColor() { return "\ncolor: " + color +
color; } " and filled: " +
filled;
public void setColor(String color) }
{this.color = color;}
}
Continue: Circle class
public class Circle extends
SimpleGeometricObject { public double getArea()
private double radius; { return radius * radius *
Math.PI; }
public Circle() { }
public double getDiameter()
public Circle(double radius)
{ return 2 * radius; }
{ this.radius = radius; }
public double getPerimeter()
public Circle(double radius, String
{ return 2 * radius * Math.PI; }
color, boolean filled)
{ this.radius = radius;
public void printCircle() {
setColor(color);
System.out.println("The circle
setFilled(filled); }
is created " + getDateCreated()
public double getRadius() + " and the radius is " +
{ return radius; } radius);
public void setRadius(double radius) }

{ this.radius = radius; } }
Continue: Class Rectangle
public class Rectangle extends
SimpleGeometricObject {
public void setWidth(double width)
private double width, height;
{ this.width = width; }
public Rectangle() { } public double getHeight()

public Rectangle( double w, double h) { return height; }

public void setHeight(double height)


{ this.width = w; this.height = h; }

public Rectangle( double w, double h, { this.height = height; }


String color, boolean filled)
public double getArea()
{ this.width = w; this.height = h;
{ return width * height; }
setColor(color); setFilled(filled);
public double getPerimeter()
} { return 2 * (width + height); }
public double getWidth() }
{ return width; }
Continue: Class Test
public class TestCircleRectangle {
public static void main(String[] args) {
Circle circle = new Circle(1);
System.out.println("A circle " + circle.toString());
System.out.println("The color is " + circle.getColor());
System.out.println("The radius is " + circle.getRadius());
System.out.println("The area is " + circle.getArea());
System.out.println("The diameter is " + circle.getDiameter());

Rectangle rectangle = new 2, 4);


System.out.println("\n A rectangle " + rectangle.toString());
System.out.println("The area is " + rectangle.getArea());
System.out.println("The perimeter is " + rectangle.getPerimeter());
}
}
Are superclass’s Constructor
?Inherited
No. They are not inherited.
 A constructor is used to construct an instance of a class.
Unlike properties and methods, a superclass's constructors
are not inherited in the subclass.
 They can only be invoked from the subclasses'
constructors explicitly, using the keyword super().
 If the keyword super() is not explicitly used, the
superclass's no-arg constructor is automatically
(implicitly) invoked.

123
Superclass’s Constructor Is Always
Invoked
A constructor may invoke an overloaded constructor or
its superclass’s constructor. If none of them is invoked
explicitly, the compiler puts super() as the first
statement in the constructor. For example,
public A() { public A() {
is equivalent to
} super();
}

public A(double d) { public A(double d) {


// some statements is equivalent to
super();
} // some statements
}

124
Using the Keyword super

The keyword super refers to the superclass of


the class in which super appears. This keyword
can be used in two ways:
To call a superclass constructor fromsub-class constructor: super() as 
a first statement in sub class constructor
)(To call a superclass method from a sub-class method: super.method 

125
Defining a Subclass
A subclass inherits from a superclass. A
:subclass can also
 Have new properties
 Have new methods
 Override the methods of the superclass

126
Calling Superclass Methods
You could rewrite the printCircle() method in the
Circle class as follows:

public void printCircle() {


System.out.println("The circle is
created " + super.getDateCreated() +
" and the radius is " + radius);
}

127
Overriding Methods in the
Superclass
A subclass inherits methods from a superclass. Sometimes it
is necessary for the subclass to modify the implementation of
a method defined in the superclass. This is referred to as
method overriding.
public class Circle extends GeometricObject {
// Other methods are omitted

/** Override the toString() method defined in GeometricObject */

public String toString() {


return super.toString() + "\nradius is " + radius;
}
}

128
NOTE
An instance method can be overridden
only if it is accessible.
Thus a private method cannot be
overridden, because it is not accessible
outside its own class.
If a method defined in a subclass is
private in its superclass, the two methods
are completely unrelated. 129
NOTE

Like an instance method, a static


method can be inherited. However, a
static method cannot be overridden.
If a static method defined in the
superclass is redefined in a subclass, the
method defined in the superclass is
hidden.
130
Overloading VS. Overriding
Overloading: is the process of having more 
than one method in the same class, or inherited
from some superclass, with the same name but
a different method signature, i.e. different types
.and/or numbers or arguments
Overriding: is the process of having more than 
one methods with same name and same
signature in super and sub class but with
different implementation. Wherein a subclass
.redefines or replaces the inherited method
Overriding vs. Overloading
public class Test { public class Test {
public static void main(String[] args) { public static void main(String[] args) {
A a = new A(); A a = new A();
a.p(10); a.p(10);
a.p(10.0); a.p(10.0);
} }
} }

class B { class B {
public void p(double i) { public void p(double i) {
System.out.println(i * 2); System.out.println(i * 2);
} }
} }

class A extends B { class A extends B {


// This method overrides the method in B // This method overloads the method in B
public void p(double i) { public void p(int i) {
System.out.println(i); System.out.println(i);
} }
} }

132
Overriding
{public class Parent public class Test{
public void method(int i) public static void main()
};System.out.println(“parent:”+i) { { Parent k = new child();
} Parent P = new Parent();
{ public class child extends Parent Child c = new child();
public void method(int i) c.metod(1);
};System.out.println(“child:”+i*2) { p.method(2);
} k.method(3);
}
}

The output is:


child 2
Parent 2
child 6
The protected Modifier
The protected modifier can be applied on data 
and methods in a class. A protected data or a
protected method in a public class can be
accessed by any class in the same package or its
subclasses, even if the subclasses are in a
.different package
private, default, protected, public 
Visibility increases

private, none (if no modifier is used), protected, public

134
Accessibility Summary

Modifier Accessed Accessed Accessed Accessed


on members from the from the from a from a different
in a class same class same package subclass package

public

protected -

default - -

private - - -

135
Visibility Modifiers
package p1;
public class C1 { public class C2 {
public int x; C1 o = new C1();
protected int y; can access o.x;
int z; can access o.y;
private int u; can access o.z;
cannot access o.u;
protected void m() {
} can invoke o.m();
} }

package p2;

public class C3 public class C4 public class C5 {


extends C1 { extends C1 { C1 o = new C1();
can access x; can access x; can access o.x;
can access y; can access y; cannot access o.y;
can access z; cannot access z; cannot access o.z;
cannot access u; cannot access u; cannot access o.u;
can invoke m(); can invoke m(); cannot invoke o.m();
} } }

136
A Subclass Cannot Weaken the
Accessibility
A subclass may override a protected
method in its superclass and change its
visibility to public.
However, a subclass cannot weaken the
accessibility of a method defined in the
superclass. For example, if a method is
defined as public in the superclass, it must
be defined as public in the subclass.
137
The final Modifier
The final class cannot be extended 
:(inherited)
{ final class Math
...
}

:The final variable is a constant 


;final static double PI = 3.14159

The final method cannot be 


.overridden by its subclasses

138
The Object Class and Its Methods
Every class in Java is descended from the
java.lang.Object class. If no inheritance is
specified when a class is defined, the
.superclass of the class is Object

public class Circle { public class Circle extends Object {


... Equivalent
...
} }

139
The toString() method in Object
The toString() method returns a string representation of the
object. The default implementation returns a string consisting
of a class name of which the object is an instance, the at sign
.(@), and a number representing this object

Loan loan = new Loan();


System.out.println(loan.toString());

The code displays something like Loan@15037e5 . This


message is not very helpful or informative. Usually you should
override the toString method so that it returns a digestible string
representation of the object.
140
The equals Method
The equals() method compares the
contents of two objects. The default implementation of
:the equals method in the Object class is as follows
public boolean equals(Object obj) {

public boolean equals(Object o) {


For example, the if (o instanceof Circle) {
equals method is return radius == ((Circle)o).radius;
overridden in }
the Circle else
return false;
class. }

141
NOTE
The == comparison operator is used for comparing
two primitive data type values or for determining
whether two objects have the same references.
The equals method is intended to test whether two
objects have the same contents, provided that the
method is modified in the defining class of the
objects.
The == operator is stronger than the equals
method, in that the == operator checks whether the
two reference variables refer to the same object.
142
The instanceof Operator

Use the instanceof operator to test whether an


:object is an instance of a class

Object myObject = new Circle();


... // Some lines of code
/** Perform casting if myObject is an instance of
Circle */
if (myObject instanceof Circle) {
System.out.println("The circle diameter is " +
((Circle)myObject).getDiameter());
...
}

143
Exercise

Use the GemotricObject class and its subclassess


:Cirlce and Rectangle to do the following
Override Object’s toString() method in Circle class to .1
.returnthe status of Circle object
Override Object’s toString() method in Rectangle class to .2
.return the status of Rectangle object
Overide Object’s equals() method to compare two circle .3
.objects
Overide Object’s equals() method to compare two .4
.Rectangle objects
.Test the above statements in the main method .5
Polymorphism

Polymorphism: the ability for a word or symbol to


.mean different things in different contexts
:Types of Polymorphism
The most common use of polymorphism in OOP occurs 
when a parent class reference is used to refer to a child
.class object
Having Methods with the same name in different classes 
with relationship or without. These methods may differ in
arguments, implementation or no change at all.
.Overriding and overloading are types of polymorphism
Polymorphism in Java
Polymorphism means that a variable of a
.supertype can refer to a subtype object
A class defines a type. A type defined by a
subclass is called a subtype, and a type defined
by its superclass is called a supertype.
Therefore, you can say that Circle is a subtype
of GeometricObject and GeometricObject is a
supertype for Circle.
PolymorphismDemo Run
146
Polymorphism, Dynamic Binding and Generic Programming
public class PolymorphismDemo {
public static void main(String[] args) { Method m takes a parameter
m(new GraduateStudent());
m(new Student()); of the Object type. You can
m(new Person());
m(new Object()); invoke it with any object.
}
  An object of a subtype can be used wherever
public static void m(Object x) {
System.out.println(x.toString()); its supertype value is required. This feature is
}
}
known as polymorphism.
 
class GraduateStudent extends Student { When the method m(Object x) is executed, the
}
  argument x’s toString method is invoked. x may be
class Student extends Person { an instance of GraduateStudent, Student, Person, or
public String toString() {
return "Student"; Object. Classes GraduateStudent, Student, Person,
} and Object have their own implementation of the
}
 
toString method. Which implementation is used will
class Person extends Object { be determined dynamically by the Java Virtual
public String toString() {
return "Person";
Machine at runtime. This capability is known as
} .dynamic binding
} Output:
Student
Student
DynamicBindingDemo Run
Person
147
java.lang.Object@b8bef7
Dynamic Binding
Dynamic binding works as follows: Suppose an object o is
an instance of classes C1, C2, ..., Cn-1, and Cn, where C1 is a
subclass of C2, C2 is a subclass of C3, ..., and Cn-1 is a
subclass of Cn. That is, Cn is the most general class, and C1
.is the most specific class
In Java, Cn is the Object class. If o invokes a method p,
the JVM searches the implementation for the method p in
C1, C2, ..., Cn-1 and Cn, in this order, until it is found. Once an
implementation is found, the search stops and the first-
.found implementation is invoked

Cn Cn-1 ..... C2 C1

Since o is an instance of C1, o is also an


Object instance of C2, C3, …,
148
Cn-1, and Cn
Method Matching vs. Binding
Matching a method signature and binding a
.method implementation are two issues
The compiler finds a matching method
according to parameter type, number of
parameters, and order of the parameters at
compilation time.
A method may be implemented in several
subclasses. The Java Virtual Machine dynamically
binds the implementation of the method at
runtime.

149
Generic Programming
public class PolymorphismDemo {
public static void main(String[] args) {
m(new GraduateStudent()); Polymorphism allows methods to be
m(new Student());
m(new Person()); used generically for a wide range of
}
m(new Object()); object arguments. This is known as
  .generic programming
public static void m(Object x) {
System.out.println(x.toString()); If a method’s parameter type is a
}
} superclass (e.g., Object), you may
 
class GraduateStudent extends Student {
pass an object to this method of any of
} the parameter’s subclasses (e.g.,
 
class Student extends Person { .Student or String)
public String toString() {
return "Student"; When an object (e.g., a Student
}
} object or a String object) is used in the
  method, the particular implementation
class Person extends Object {
public String toString() { of the method of the object that is
return "Person"; invoked (e.g., toString) is determined
}
} .dynamically

150
Casting Objects
You have already used the casting operator to convert
variables of one primitive type to another. Casting can
also be used to convert an object of one class type to
.another within an inheritance hierarchy
In the preceding section, the statement
m(new Student());

assigns the object new Student() to a parameter of the


:Object type. This statement is equivalent to

Object o = new Student(); // Implicit casting


m(o);
The statement Object o = new Student(), known as
implicit casting, is legal because an instance of
Student is automatically an instance of Object.
151
?Why Casting Is Necessary
Suppose you want to assign the object reference o to a variable of
:the Student type using the following statement

Student b = o; //A compiler error would occur


 
Why does the statement Object o = new Student() work and the
?statement Student b = o doesn’t
This is because a Student object is always an instance of Object, but
.an Object is not necessarily an instance of Student
Even though you can see that o is really a Student object, the
.compiler is not so clever to know it
.To tell the compiler that o is a Student object, use an explicit casting
The syntax is similar to the one used for casting among primitive data
types. Enclose the target object type in parentheses and place it
:before the object to be cast, as follows
Student b = (Student)o; // Explicit casting
152
Casting from
Superclass to Subclass

Explicit casting must be used when


casting an object from a superclass to a
subclass. This type of casting may not
.always succeed
Apple x = (Apple)Fruit; //Fruit is superclass

Orange x = (Orange)Fruit;

153
TIP
To help understand casting, you may also
consider the analogy of fruit, apple, and
orange with the Fruit class as the
superclass for Apple and Orange. An
apple is a fruit, so you can always safely
assign an instance of Apple to a variable
.for Fruit
However, a fruit is not necessarily an
apple, so you have to use explicit casting
to assign an instance of Fruit to a variable
.of Apple
154
Meeting 7: Abstract Classes
and Interfaces.

Edited by: Dr. Bayan Abu Shawar


AOU-Jordan
Objectives
 To design and use abstract classes.

 To specify common behavior for objects using interfaces.

 To define interfaces and define classes that implement interfaces.

 To define a natural order using the Comparable interface.

 To explore the similarities and differences among concrete

classes, abstract classes, and interfaces.

 To design classes that follow the class-design guidelines.

156
Abstract method in Abstract class
An abstract class defines a common set of methods and a
common set of instance variables for its subclasses. An
abstract class should contain at least one abstract method.
An abstract method: a method header defined in a class
without implementation.
One cannot create instances of abstract classes.
Abstract classes are specified in the class header using the
Java keyword abstract.

public abstract class Class_Name{


………………..
………………..
public abstract return_data_type method_name();
}
157
Abstract Class & Concrete class
A concrete sub class is needed to extend an abstract 
class, and the sub class should implement the abstract
.method using the same method header (overridden)
Concrete class: is a fully implemented class, with no 
.abstract methods
.Concrete methods: a fully implemented methods 

The concrete subclass that is extended from an abstract 


class, should implement all the abstract methods, even if
.they are not used in the subclass
Abstract Class

Abstract classes usually define abstract


methods, that are then overridden in the
.concrete classes derived from them
It is possible to declare variables of an
.abstract class type
It is not possible to create objects of an
.abstract class
Abstract Class & abstract methods
?When to use abstract classes 
Usually when you have many classes that have common 
:features
1. Common attributes,
2. Common methods, that has the same signature and
implementation.
3. Common methods that has the same signature but
different implementation.
In this case you create an abstract class (Super class) that has all the 
common features, wherein the common methods that have same signature
.but different implementation are represented as abstract methods
And you will need concrete subclasses to complete the implementation of 
.abstract methods
Abstract Classes and Abstract Methods

GeometricObject
Circle

Rectangle

TestGeometricObject

Run

161
Example: SimpleGeometricObject Class
import java.util.Date;
public class GeometricObject { public boolean isFilled()
private String color = "white"; { return filled; }
private boolean filled;
private Date dateCreated; public void setFilled(boolean filled)
{ this.filled = filled;}
protected GeometricObject() {
dateCreated = new java.util.Date(); public Date getDateCreated()
} {
protected GeometricObject(String return dateCreated;
color, boolean filled) { }
dateCreated = new Date();
this.color = color; public String toString() {
this.filled = filled; return "created on " +
} dateCreated +
public String getColor() { return "\ncolor: " + color +
" and filled: " +
color; }
filled;
}
public void setColor(String color)
{this.color = color;}
public abstract double getArea();
public abstract double getPremieter();

}
Continue: Circle class
public class Circle extends
GeometricObject { public double getDiameter()
private double radius; { return 2 * radius; }

public Circle() { } public double getArea()


{ return radius * radius *
public Circle(double radius)
Math.PI; }
{ this.radius = radius; }
public double getPerimeter()
public Circle(double radius, String
{ return 2 * radius * Math.PI; }
color, boolean filled)
{ this.radius = radius;
setColor(color); public String toString() {
setFilled(filled); } return ("The circle is " +
public double getRadius() super.toString()+
{ return radius; }
" and the radius is " +
public void setRadius(double radius)
radius);
{ this.radius = radius; }
}
}
Continue: Class Rectangle
public class Rectangle extends
SimpleGeometricObject {
public void setHeight(double height)
private double width, height;
{ this.height = height; }
public Rectangle() { }
public double getArea()
public Rectangle( double w, double h)
{ return width * height; }
{ this.width = w; this.height = h; }
public double getPerimeter()
public Rectangle( double w, double h, { return 2 * (width + height); }
String color, boolean filled)
public String toString() {
{ this.width = w; this.height = h;
return "The rectangle is " +
setColor(color); setFilled(filled);
super.toString()+
} " the height = " + height+
public double getWidth()
"width =" + width;
{ return width; }
public void setWidth(double width) }

{ this.width = width; } }
public double getHeight()
{ return height; }
Abstract class without abstract method

A class that contains abstract methods must


be abstract. However, it is possible to define
an abstract class that contains no abstract
methods. In this case, you cannot create
instances of the class using the new operator.
This class is used as a base class for defining
a new subclass.

165
superclass of abstract class may be
concrete

A subclass can be abstract even if its


superclass is concrete. For example, the
Object class is concrete, but its subclasses,
such as GeometricObject, may be abstract.

166
Concrete method overridden to be
abstract
A subclass can override a method from its
superclass to define it abstract. This is rare,
but useful when the implementation of the
method in the superclass becomes invalid in
the subclass. In this case, the subclass must be
defined abstract.

167
Abstract class as type
You cannot create an instance from an abstract class
using the new operator, but an abstract class can be
used as a data type. Therefore, the following
statement, which creates an array whose elements
are of GeometricObject type, is correct.
GeometricObject[] geo = new GeometricObject[10];

NOTE: We are not creating Gemoetric objects; only


Geometric references.

168
Continue
We can then store references to objects of any subclass of 
.GeometricObjects in the array, e.g
;geo[0] = new Circle(5) 
;geo[1] = new Rectangle(3,4) 

We can use geo[] to call any method in 


GeometricObject class, in case of abstract methods the
overridden concrete ones will be invokes based on the
.type
;System.out.println(geo[0].getArea()) 
.This will invoke getArea() of Circle Class 
However, you could not call geo[0].getRadius() because geo[] is 
of type GemotricObject class and getRadius() is not a method
.there

Interfaces

What is an interface?
Why is an interface useful?
How do you define an interface?
How do you use an interface?

170
What is an interface?
? Why is an interface useful
An interface is a classlike construct that
contains only constants and abstract methods.

An interface specifies a list of methods that a


group of unrelated classes should implement,
so that their instances can interact together by
responding to a common subset of messages.

171
Interfaces

In many ways, an interface is similar to an


abstract class, but the intent of an interface
.is to specify common behavior for objects

For example, you can specify that the


objects are comparable, edible, cloneable
.using appropriate interfaces
Interfaces
:Interfaces are “like” classes, but they may ONLY have 

Abstract methods, i.e. method header but NO method .1


.code
• All methods in an interface are automatically public.
• No need to writ public in the method header.

.Constants, but NO instance variables .2


• All constants in an interface are automatically public static final.
• Note that an interface is NOT a class and will have NO instances of
its own, and so it has NO attributes and NO constructor.
?Why is an interface useful
To have unrelated classes implement similar 
methods (behaviors)
To model multiple inheritance (i.e. to “inherit” 
from multiple interfaces) – you want to impose
.multiple sets of behaviors to your class
Some Java methods can be applied to objects 
only if implement certain interfaces
Interface is a Special Class
An interface is treated like a special class in
Java. Each interface is compiled into a separate
bytecode file, just like a regular class.
Like an abstract class, you cannot create an
instance from an interface using the new
operator, but in most cases you can use an
interface more or less the same way you use an
abstract class.
For example, you can use an interface as a
data type for a variable, as the result of casting,
and so on.
175
Define an Interface
To distinguish an interface from a class, Java
uses the following syntax to define an interface:
public interface InterfaceName
{
constant declarations;
abstract method signatures;
}
Example:
public interface Edible {
/** Describe how to eat */
public abstract String howToEat();
}

176
?How to use an Itnerface

To make use of an interface we need a 


.class to implement the interface
The class does this by providing the code 
.for any abstract methods in the interface

public class Chicken implements Edible{


……
public String howToEat() { }
} 
Example
You can now use the Edible interface to specify whether an object is
edible. This is accomplished by letting the class for the object
implement this interface using the implements keyword. For
example, the classes Chicken and Fruit implement the Edible
interface (See TestEdible).

Edible TestEdible Run


178
Edible Interface
{ public interface Edible
;)(public abstract String howToEat
}

public class Chicken extends Animal implements Edible {


public String howToEat() { return "Chicken: Fry it"; }
public String sound() { return "Chicken: cock-a-doodle-doo"; }
}
Omitting Modifiers in Interfaces
All data fields are public final static and all methods
are public abstract in an interface.
For this reason, these modifiers can be omitted, as
shown below:

public interface T1 { public interface T1 {


public static final int K = 1; Equivalent int K = 1;

public abstract void p(); void p();


} }

A constant defined in an interface can be accessed using


syntax InterfaceName.CONSTANT_NAME (e.g., T1.K).

180
Example: The Comparable
Interface
// This interface is defined in
// java.lang package
package java.lang;

public interface Comparable<E>


{
public int compareTo(E o);

181
Example
1 System.out.println(new Integer(3).compareTo(new Integer(5)));
2 System.out.println("ABC".compareTo("ABE"));
3 java.util.Date date1 = new java.util.Date(2013, 1, 1);
4 java.util.Date date2 = new java.util.Date(2012, 1, 1);
5 System.out.println(date1.compareTo(date2));

182
The Comparable Interface
.This interface allows comparing or sorting objects 
Any class that implements the Comparable interface must have a 
met
.>< The type that the comparison will involve is added in 
The compareTo method allows the class to define an appropriate 
.measure of comparisonhod compareTo
Defining Classes to Implement
Comparable

ComparableRectangle SortRectangles Run

184
ComparableRectangl Class
public class ComparableRectangle extends Rectangle implements 
{ >Comparable<ComparableRectangle
public ComparableRectangle(double width, double height) 
{ super(width, height); }
{ public int compareTo(ComparableRectangle o) 
if (getArea() > o.getArea()) 
;return 1 
else if (getArea() < o.getArea()) 
;return -1 
else 
} ;return 0 

{ )(public String toString 


" :return "Width: " + getWidth() + " Height: " + getHeight() + " Area 

};)(getArea + 
} 
Multiple inheritance in Java is not
allowed
Java avoids multiple inheritance problems 
.by the use of interfaces
Class can implement more than one 
interface, and extend one class ONLY–
this gives an alternative to multiple
.inheritance
public class MonthlyEmployee 
} { extends Employee implements Comparable, Serializable 
Exercise
Interfaces vs. Abstract Classes

In an interface, the data must be constants; an abstract


class can have all types of data.
Each method in an interface has only a signature without
implementation; an abstract class can have concrete
methods.
All classes share a single root, the Object class, but there is
no single root for interfaces.

188
Interfaces vs. Abstract Classes
DIFFERENCES 
:Interface 
.An interface is not a class 
All its methods are abstract 
.Only constant data is allowed 
An interface can be implemented by any number of unrelated classes, which declare 
.this using the implements keyword. A class may implement any number of interfaces
:Abstract class 
.An abstract class uses the keyword abstract in the class header 
It normally has at least one abstract method, either defined within the class or 
inherited from a superclass, and its abstract methods must be explicitly declared
.abstract
It can also have concrete methods (that is, it may be fully implemented) 
.It can also have instance variables, unlike an interface 
It can only constrain its own concrete subclasses, by requiring them to implement its 
.abstract methods
All classes share a single root, the Object class, but there is no single root for 
.interfaces
Interfaces vs. Abstract Classes
SIMILARITIES 
.They can both place requirements on objects of other classes 
Both can have abstract methods (although neither need have 
.abstract methods)
You cannot create objects of an abstract class type or an interface 
.type
You can create reference variables of either type. These are 
normally used to refer to an object of a subclass of the abstract type
.or to an object of a class that implements the interface, respectively
Both can inherit: the abstract class from another class; the interface 
.only from another interface
?Whether to use an interface or a class
Abstract classes and interfaces can both be used to model common
features.

How do you decide whether to use an interface or a class?


In general, a strong is-a relationship that clearly describes a parent-child
relationship should be modeled using classes. For example, a staff
member is a person.
A weak is-a relationship, also known as an is-kind-of relationship,
indicates that an object possesses a certain property. A weak is-a
relationship can be modeled using interfaces.
For example, all strings are comparable, so the String class implements
the Comparable interface. You can also use interfaces to circumvent
single inheritance restriction if multiple inheritance is desired. In the case
of multiple inheritance, you have to design one as a superclass, and
others as interface.

191
Guidelines for Designing a Class
A class should describe a )Coherence(
single entity, and all the class operations
should logically fit together to support a
.coherent purpose
You can use a class for students, for
example, but you should not combine
students and staff in the same class, because
.students and staff have different entities
.Designing a Class, cont
A single entity with too many )Separating responsibilities(
responsibilities can be broken into several classes to
.separate responsibilities
The classes String, StringBuilder, and StringBuffer all deal
.with strings, for example, but have different responsibilities
.The String class deals with immutable strings
.The StringBuilder class is for creating mutable strings
The StringBuffer class is similar to StringBuilder except
that StringBuffer contains synchronized methods for
.updating strings
.Designing a Class, cont
Classes are designed for reuse. Users
can incorporate classes in many different
combinations, orders, and environments.
Therefore, you should design a class that
imposes no restrictions on what or when
the user can do with it. To do this follow
:the below instructions
.Designing a Class, cont
Design the properties (attributes) to ensure that the user can set
,properties in any order, with any combination of values
.Design methods to function independently of their order of occurrence
.Provide a public no-arg constructor

override the equals() method and the toString() method defined in
.the Object class whenever possible
.Follow standard Java programming style and naming conventions
.Choose informative names for classes, data fields, and methods
Always place the data declaration before the constructor, and place
.constructors before methods
Always provide a constructor and initialize variables to avoid
.programming errors
Using Visibility Modifiers
Each class can present two contracts – one for the users
.of the class and one for the extenders of the class
Make the fields private and accessor methods public if
.they are intended for the users of the class
Make the fields or method protected if they are intended
.for extenders of the class
The contract for the extenders encompasses the
.contract for the users
The extended class may increase the visibility of an
instance method from protected to public, or change its
implementation, but you should never change the
.implementation in a way that violates that contract
.Using Visibility Modifiers, cont
A class should use the private modifier to hide its
.data from direct access by clients
You can use get methods and set methods to provide
users with access to the private data, but only to private
.data you want the user to see or to modify
A class should also hide methods not intended for
client use. In this case the method is declared as
private and only used by another method inside the
.class. This is know as helper method
Using the static Modifier

A property that is shared by all the


instances of the class should be
.declared as a static property
Meeting 8: Exception Handling
and Text IO.

Edited by: Dr. Bayan Abu Shawar


AOU-Jordan
Motivations

When a program runs into a runtime error, the


program terminates abnormally. How can you
handle the runtime error so that the program
can continue to run or terminate gracefully?
This is the subject we will introduce in this
.chapter

200
Objectives
Introduction .1
Input and output streams .2
Reading text input .3
Writing text output to a file .4
Reading from a Web .5
Exceptions .6
Declaring and handling exceptions .7

201
Introduction
:In this meeting, we aim to study 

Inputs and Outputs 


There are 2 ways for input/output:
1. communicating with a sequential source or destination (such as
a file, a keyboard or another computer).
2. using a graphical user interface (studied later).

Error Handling 
We show how to deal with error conditions in a Java program, by 
;means of exceptions or otherwise 

202
Input-Output Streams
.Java relies on the concept of a stream for providing its input/output facilities 
A stream is essentially a sequence of bytes, representing a flow of 
.data from a source to a destination

:Sources and destinations include 


 keyboard,
 Screen
 various sorts of data files,
 and between networked computers.
:Any read or write is performed in three simple steps 
Step 1. Open the stream: you need to define some objects here 
Step 2. Keep reading from or writing to files as long as there are You 
.need to use the methods of the objects defined in step1 to read the stream 
.Step 3. Close the stream 

.All the streams provided in Java can be found in the java.io package 
;*.Any program that uses streams needs to include the statement: import java.io 
203
Reading text from the keyboard using
Scanner class

import java.util.*;
Import
java.util.* library that includes try{
the Scanner class
Scanner sc = new Scanner(System.in);
Step1: define a Scanner object, String s = sc.nextLine();
sc or any name. To take input from System.out.println(s);
the keyboard, use (System.in).
sc.close();
}
Step2: use the Scanner object
catch(FileNotFoundException e){
to get data.
System.out.println(e);
Step3: close the Scanner when }
finished using it!
204
Reading text from a File using
Scanner class
Import import java.util.*;
java.util.*; library that includes import java.io.*;
the Scanner class.
java.io.*; that includes File class.
try{
Step1.1: create a File object that File fr = new File(“C:/test.txt”);
points to your text file. Scanner sc = new Scanner(fr);
Step 1.2: define a Scanner object, String s = sc.nextLine();
sc or any name. To take input from
System.out.println(s);
the text file, use the file object you
created in Step1.1 sc.close();
}
Step2: use the Scanner object catch(FileNotFoundException e){
to get data. System.out.println(e);
}
Step3: close the Scanner when
finished using it! 205
Common Scanner Methods
:Input methods 
s = sc.next() Returns next “token” (i.e. "word“).
s = sc.nextLine() Returns an entire input line as a String.
i = sc.nextInt() Returns next integer value.
d = sc.nextDouble() Returns next double value.

:Test methods (used for error checking and loops) 


b = sc.hasNext() True if another token is available to be read.
b = sc.hasNextLine() True if another line is available to be read.
b = sc.hasNextInt() True if another int is available to be read.
b = sc.hasNextDouble() True if another double is available to be read.

206
Writing text to a file using
PrintWriter class
import java.io.*;
Import
java.io.*; that includes File class.
try{
File fw = new File(“C:/test.txt”);
Step1.1: create a File object that
PrintWriter pr = new PrintWriter(fw);
points to your text file.
Step 1.2: define a PrintWriter pr.println(“Enjoy M251 module”);
object, pr or any name, which you pr.println(“Good Luck”);
can use it to write into the text file, pr.close();
use the file object you created in }
Step1.1 catch(FileNotFoundException e){
Step2: use the PrintWriter object System.out.println(e);
to write data. }

Step3: close the PrintWriter when Note: Any data in the test.txt file will
finished using it! be erased before writing the new
data using println method.
207
Exercise(1)
Write a Java code to write the following lines .1
into a new text file: luck.txt
Study well for the final exam
It will be an easy exam
Just study well and concentrate during the exam
Good luck.

  
Then write another Java code to print the .2
contents of luck.txt file, and to print the number
.of lines in the file

208
Solution 1.1
;"String name = "D:\luck.txt 
;File fw = new File(name) 
  
{try 
;PrintWriter wr = new PrintWriter(fw) 
;wr.println("Study well for the final exam") 
;wr.println("It will be an easy exam") 
;wr.println("Just study well and concentrate during the exam") 
;wr.println("Good Luck") 
;)(wr.close 
} 
catch(Exception e) 
} ;System.out.println("Error: "+ e) { 

209
Solution 1.2
;"String name = "D:\luck.txt 
;File fr = new File(name) 
{try 
;Scanner readfrom = new Scanner(fr) 
;String s; int count=0 
while(readfrom.hasNextLine()) 
{ 
;++s = readfrom.nextLine(); count 
;System.out.println(s) 
} 
;)(readfrom.close 
;System.out.println(“Number of lines in the file is: ”+ count) 
} 
catch(Exception e)  
} ;System.out.println("Error"+ e) { 
210
Reading/Writing Objects
To make an object persistent, the state of an object 
should be stored in a file. So you could write states of
objects in a file, or you could use data in stored file to
.create new objects
you need to access each attribute for reading or writing 
using for example: objectName.getX() or
;)(objectName.setX
In order to print content of an ArrayList of Circls, 
Rectangles, etc. You need to use for each and access
.each attribute using getter method

211
Exercise(2)
:Create a new class: Deal_Rectangles that has the following methods 
 Write a static method to fillRectangles() that take a list of objects as an
argument and fill it with rectangle objects.
 Write a static Java method writeToFile() to write a list of rectangles into a
text file: “rectangles.txt“.
 Write a static Java method readFromFile() to read content of
“rectangles.txt”, and return contents as a list.
 Write a static Java method printArea() which takes the list returned from
redFromFile() method and print area of each rectangle in the list.
 Create a list of recangles in main method, then invoke fillRectangles()
and writeToFile(), readFromFile().

Note that: Rectangle constructor takes 3 arguments: width, height, and 


.color
212
Solution Exercise(2)
import java.util.*;
import java.io.*;
import ou.*;
public class Deal_Rectangles
{
public static void create(ArrayList<Rectangle> list)
{
Rectangle r1 = new Rectangle(3,5,"Pink");
Rectangle r2 = new Rectangle(6,6,"Red");
Rectangle r3 = new Rectangle(8,9,"Yellow");
list.add(r1);
list.add(r2);
list.add(r3);
} 213
{public static void writeToFile(ArrayList<Rectangle> list) 
{try 
;File f = new File("c:/rectangles.txt") 
;PrintWriter pr = new PrintWriter(f) 
for(Rectangle x: list) 
+)(pr.println(x.getWidth()+" "+x.getHeight 
;))(x.getColor+" " 
;)(pr.close 
} 
{catch(IOException e) 
;System.out.println("there is an error: "+e) 
} 
} 

214
{)(public static ArrayList<Rectangle> readFromFile 
;)(>ArrayList<Rectangle> list = new ArrayList<Rectangle 
Note that: you need to {use: try 
;File f = new ): when 
File("c:/rectangles.txt")
owhile(s.hasNext()
;Scanner
you want s = to read
new each
Scanner(f) 
element
;double in w, the line and
h; String colorstore 
it in a different variable.
{ while(s.hasNext()) 
owhile(s.hasNextLine() ):
;)(w = s.nextDouble(); h = s.nextDouble 
when you need to read a
whole line ;)(color
as a =string,
s.next or 
;list.add(newcount number of lines in a file
Rectangle(w,h,color))
as in the solution of
while// } 
exercise(1.2), in this case
also while(s.hasNext();)(s.close): will 
work. try// } 
catch(Exception e){ System.out.println("there is an error: "+e); } 
;return list 
} 
215
{public static void printArea(ArrayList<Rectangle> list) 
for(Rectangle x : list) 
;System.out.println(x.getArea()) 
} 
end of class Deal_Rectangle//} 

import java.util.*;
public class Meeting7_ex2 {
public static void main(String[] args) {
ArrayList<Rectangle> list, list1;
list = new ArrayList<Rectangle>();
Deal_Rectangles.create(list);
Deal_Rectangles.writeToFile(list);
list1 = Deal_Rectangles.readFromFile();
Writing_Rectangles.printArea(list1);
}
} 216
Exceptions

An exception is an event, which occurs during the execution of a


program, that stops the normal flow of the program's instructions.

An Exception describes errors caused by your program and external


circumstances. These errors can be caught and handled by your
program.

217
When to use Exception Handling
Java's Exception Handling can be used to deal with potentially serious or 
.unpredictable error conditions
Examples of serious errors that could occur within a Java program are as 
:follows

;a program tries to read past the end of a data file 


;a program cannot find a specified input file 
;a program tries to connect to a website using an invalid address 
;a program runs out of memory 
a method tries to access an array element whose index is larger than the 
;upper limit of the array
an overflow condition occurs when the result of some arithmetic operation 
;exceeds the limit for the primitive data types involved
;a program expecting to read a file of integers finds a string value in the file 
.a method expecting an object reference encounters a null reference instead 

218
Example of: InputMismatchException

Exception handling – example- the user 


entered a character instead of an int number – then an
.error occurred, (InputMismatchException)

219
Exception Types
The Throwable class represents the ClassNotFoundException
most general class for describing
exceptions. ArithmeticException
IOException

Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException

Many more classes


LinkageError

Error VirtualMachineError

Many more classes

220
System Errors
Exceptions that should not be caught or declared
ClassNotFoundException

ArithmeticException
IOException

Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException

Many more classes


LinkageError
System errors are thrown by JVM
Error VirtualMachineError and represented in the Error class.
The Error class describes internal
system errors. Such errors rarely
Many more classes
occur. If one does, there is little
you can do beyond notifying the
user and trying to terminate the
program gracefully.
Exceptions
Exception describes errors
caused by your program ClassNotFoundException
and external ArithmeticException
circumstances. These IOException
errors can be caught and Exception NullPointerException
handled by your program.
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException

Many more classes


LinkageError

Error VirtualMachineError

Many more classes

222
Runtime Exceptions
Exceptions that Need not be caught or declared

ClassNotFoundException

ArithmeticException
IOException

Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException

Many more classes


LinkageError
RuntimeException is caused
Error VirtualMachineError by programming errors, such
as bad casting, accessing an
out-of-bounds array, and
Many more classes
numeric errors.

223
Unchecked Exceptions
Error, and RunTime Exception
ClassNotFoundException

ArithmeticException
IOException

Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException

Many more classes


LinkageError

Unchecked
Error VirtualMachineError Exception: No
need to caught or
Many more classes declared.

224
Unchecked Exception
Exceptions that Need not be caught or declared
Unchecked Exceptions: reflects an error in programming. 
The programmer has failed to take into account a problem which
was predictable and should have been treated. It could be treated
.using if-Statement or try-catch
:For example 
 ArrayIndexOutOfBoundsException occurs when a program tries to
access an array with an index outside the valid limits.
 ArithmeticException arises when an illegal arithmetic condition
occurs, such as an attempt to divide an integer by zero.
 NumberFormatException can be caused by an application expecting
to read a number of some sort, when the data does not have the
appropriate format.
 NullPointerException happens when an application attempts to use
null in a case where an object is required: for example, invoking a
method on a null reference.

225
Checked Exceptions vs.
Unchecked Exceptions

The subclasses of Throwable


can be categorise into :
1. Unchecked Exceptions:
which includes
RuntimeException, Error and
their subclasses.
2. Checked Exceptions: which
include all other exceptions
except RuntimeException.

226
Checked Exception
Checked Exceptions: meaning that the compiler forces the 
programmer to check and deal with the exceptions. This could be
achieved using try-catch or throws. Checked exceptions relate to
problems that can be foreseen but cannot necessarily be detected
.before they occur
:For example 
 EOFException occurs when a program attempts to read past the
end of a file.

 FileNotFoundException can occur when a program attempts to


open or write to an existing file, but the file is not found.

 MalformedURLException indicates that an invalid form of URL


(such as a website address) has occurred.

227
Exception Handling
:Exception handling works as illustrated below 

When Java system detects an error, it stops the normal flow of .1


.program execution. We say here the code throws an exception

A special kind of Java object, known as an exception object, is .2


created. This object holds some information about what has gone
.wrong

The exception handler catches the exception, wherein the control is .3


transferred from the part of your program where the occurred to an
.exception handler, which deals with the situation

The exception object is available to the exception handler code and .4


.can be used to help decide on the appropriate action

228
Handling Checked Exception

:For checked exception, you must do one of two things 


Declare in the method header that an exception may be .1
thrown. In this case you do not handle the exception
within the method, but simply pass it on using throws
.keyword

Catch the exception and deal with it within the method, .2


.using a try-catch statement (Handling exceptions)

229
Handling Checked Exception using
throws keyword
When declaring an exception in the 
method header, you use the keyword
throws followed by the type of
.exception expected
Example1: If the method 
unexpectedly came to the end of the
file when expecting to read more
data, then the method would
generate an exception of type public boolean checkFormat(String fileName)
.EOFException
throws EOFException, MalformedURLException
Example2: A method may be capable 
of generating more than one type of {
checked exception. In this case you
//Code for method
.need to list all the possible types
}
Example3: If some or all of the 
possible exception types in a list are
subclasses of a particular exception
class, it may be possible to shorten
the list. This works because
EOFException and
MalformedURLException are
.subclasses of IOException
230
Handling Checked Exception using try-
catch statements (Catching Exception)
To deal with an exception that has been thrown, we use a try-catch 
.statement
.Each try should be followed by at least 1 catch 
When this handler code is executed, the variable within the catch 
clause will contain a reference to the exception object that has been
.thrown
try {
statements; // Statements that may throw exceptions
}
catch (Exception1 exVar1) {
handler for exception1;
}
catch (Exception2 exVar2) {
handler for exception2;
}
...
catch (Exceptionn exVar3) {
handler for exceptionn;
} 231
Example of Catching an Exception
public static void main(String[] args) { public static void main(String[] args) {
try{ try{
File myFile = new File("C:/test.txt"); File myFile = new File("C:/test.txt");
Scanner sc = new Scanner(myFile); Scanner sc = new Scanner(myFile);
String s = sc.nextLine(); String s = sc.nextLine();
System.out.println(s); System.out.println(s);
sc.close(); sc.close();
} }
catch(FileNotFoundException e){ catch(Exception e){
System.out.println(e); System.out.println(e);
} }
} }

It is best to be as specific as possible about the type of 


exception you expect to be generated. For example, it is 
.usually a bad idea to do this in the above code 
232
Advantage of Handling Exceptions

The advantages of using exception handling. It 


enables a method to throw an exception to its
caller. Without this capability, a method must
.handle the exception or terminate the program

233
Cautions When Using Exceptions

Exception handling separates error-handling code 


from normal programming tasks, thus making
.programs easier to read and to modify
Be aware, however, that exception handling 
usually requires more time and resources
because it requires instantiating a new exception
object, rolling back the call stack, and propagating
.the errors to the calling methods

234
When to Throw Exceptions
An exception occurs in a method. If you want 
the exception to be processed by its caller,
you should create an exception object and
.throw it
If you can handle the exception in the method 
where it occurs, there is no need to throw it.
you can handle it using If-Statement, which is
.the case with Unchecked Exception

235
When to Use Exceptions
?When should you use the try-catch block in the code
o You should use it to deal with unexpected error conditions,

(checked Exceptions).
o Do not use it to deal with simple, expected situations.

:For example, the following code


try {
System.out.println(refVar.toString());
}
catch (NullPointerException ex) {
System.out.println("refVar is null");
} 236
When to Use Exceptions
Unchecked Exceptions: is better to be replaced by if-
.statement which is know as defensive programming

if (refVar != null)
System.out.println(refVar.toString());
else
System.out.println("refVar is null");

Defensive programming techniques are appropriate when the potential


error is
more localized and predictable – for example, checking that a queue is
not full before attempting to add a new element.
Exception handling is typically much slower in execution than standard
error handling techniques – this 237 is a reason to use it with checked
exceptions mainly.
The finally Clause
Cleaning up: the finally clause
One of the things we often want to do after an exception has occurred is to
'clean up' by releasing any resources such as memory or files that a method
has been using before the exception was thrown. This allows these resources
to be used by other parts of the program or other programs.
To deal with this, Java provides another facility in the try statement – the
finally clause.
Code in the finally clause will be executed at the end of the try statement,
whether or not execution was interrupted by an exception.

{ try
;statements
}
{ catch(TheException ex)
;handling ex
}
{ finally
;finalStatements
238 }
animation

Trace a Program Execution


Suppose no
exceptions in the
statements
{ try
;statements
}
{ catch(TheException ex)
;handling ex
}
{ finally
;finalStatements
}

;Next statement
239
animation

Trace a Program Execution


The final block is
{ try always executed
;statements
}
{ catch(TheException ex)
;handling ex
}
{ finally
;finalStatements
}

;Next statement

240
animation

Trace a Program Execution


Next statement in
{ try the method is
executed
;statements
}
{ catch(TheException ex)
;handling ex
}
{ finally
;finalStatements
}

;Next statement
241
animation

Trace a Program Execution


{ try Suppose an exception
;statement1 of type Exception1 is
;statement2 thrown in statement2
;statement3
}
{ catch(Exception1 ex)
;handling ex
}
{ finally
;finalStatements
}

;Next statement

242
animation

Trace a Program Execution


{ try The exception is
;statement1 handled.
;statement2
;statement3
}
{ catch(Exception1 ex)
;handling ex
}
{ finally
;finalStatements
}

;Next statement

243
animation

Trace a Program Execution


{ try The final block is
;statement1 always executed.
;statement2
;statement3
}
{ catch(Exception1 ex)
;handling ex
}
{ finally
;finalStatements
}

;Next statement

244
animation

Trace a Program Execution


{ try The next statement in
;statement1 the method is now
;statement2 executed.
;statement3
}
{ catch(Exception1 ex)
;handling ex
}
{ finally
;finalStatements
}

;Next statement

245
Meeting 9-10: JavaFX Basics

Edited by: Dr. Bayan Abu Shawar


AOU-Jordan
Objectives
.To create user interfaces using panes, UI controls, and shapes 
To layout nodes using Pane, StackPane, FlowPane, GridPane, 
. BorderPane, HBox, and VBox
Creating different UI controls: Buttons, labels, textfield, textArea, CheckBox, 
.and RdioButton
To display text using the Text class and create shapes using Line, Circle, 
.Rectangle, Ellipse, Arc, Polygon, and Polyline
. To get a taste of event-driven programming 
.To describe events, event sources, and event classes 
To define handler classes, register handler objects with the source object, 
.and write the code to handle events
. To define handler classes using inner classes 
.To define handler classes using anonymous inner classes 
. To simplify event handling using lambda expressions 
. To write programs to deal with MouseEvents 
. To write programs to deal with KeyEvents 
Introduction
JavaFX is a new framework for developing Java 
.GUI (Graphical User Interface) programs

Swing and AWT are replaced by the JavaFX 


.platform for developing rich Internet applications

GUI programs will include visual components 


such as: buttons, areas for typing in text, drop-
down menus for selecting options, areas for
displaying results, and so on. Those are known
.as User Interface Controls (UI Controls)
Basic Structure of JavaFX

Application 
Override the start(Stage) method 
Stage, Scene, and Nodes 
Stage
Scene

Button
MyJavaFX Run

MultipleStageDemo Run

249
Continue: Basic Structure of JavaFX
A JavaFx class must extend 
javafx.application.Application and overrides the start
.method

A stage (theater) is a window for displaying a scene. A Stage object 


called primary stage is automatically created by the JVM when the
.application is lunched

A scene is an object that can be created using the constructor: 


Scene(node, width, height)

This constructor specify the width and height of the scene. 


.(create a window with certain size that will hold the nodes)

Nodes(actors) that perform in the scenes. Panes, groups, controls, 


.and shapes are nodes
Panes, UI Controls, and Shapes
A node is a visual component such as: a Shape, an 
.Image view, a UI Control, a Group or a Pane
A Shape refers to a text, line, circle, ellipse, rectangle, 
.etc
A Pane is a container class that is used for automatically 
.laying out the nodes in a desired location and size
A Group is a container that groups a collection of nodes. 
You can apply transformation or effects to a group, which
.automatically apply to all the children of the group
A UI Control refers to a label, button, check box, radio 
.button, text field, text area, anjd so on
Building GUI
.Create a class that extends Application class .1
.Override the start method that will hold all your Java statements .2
}….…………{public void start(Stage primaryStage) 
.Create your nodes, UI controls: buttons, labels, etc .3
;Button btOK = new Button("OK") 
.Create and Place nodes in a scene .4
;Scene scene = new Scene(btOK, 200, 250) 
;Place the Scene in a stage. primaryStage.setScene(scene) .5
;Set Stage title. primaryStage.setTitle("MyJavaFX") .6
;)(Display the stage. primaryStage.show .7
Write Application.launch(args); in the main method to run .8
.the application
Needed Java Librarues to build
JavaFX GUI

;import javafx.application.Application 
;import javafx.scene.Scene 
;*.import javafx.scene.control 
;import javafx.stage.Stage 
Example(1)
{ public class MyJavaFX extends Application 
Override // Override the start method in the Application@ 
{ public class public void start(Stage primaryStage)
Create a button and place it in the scene // 
;Button btOK = new Button("OK") 
;Scene scene = new Scene(btOK, 200, 250) 
primaryStage.setTitle("MyJavaFX"); // Set the stage title 
primaryStage.setScene(scene); // Place the scene in the stage 
primaryStage.show(); // Display the stage 
} 
The main method is only needed for the IDE with limited * JavaFX * **/ 
/* .support. Not needed for running from the command line
public static void main(String[] args) { launch(args); } 
}
OutPut
Note that: The displayed button is always
centered in the scene and occupies the
.entire window
You can use container classes called
Panes, for automatically laying out the
.nodes in a desired location and size
:You need to
1. place nodes inside a pane then
2. place the Pane into the Scene.
Panes, UI Controls, and Shapes
A Scene can contain a
control, Group, or a Pane, but
not a Shape or an
ImageView.

A Pane or a Group can


contain any subtype of Node.

Group

256 ButtonInPane Run


Binding Properties

JavaFX introduces a new concept called


binding property that enables a target object to
be bound to a source object. If the value in the
source object changes, the target property is
also changed automatically. The target object is
simply called a binding object or a binding
.property

ShowCircleCentered Run

257
Layout Panes
JavaFX provides many types of panes for organizing
.nodes in a container

258
FlowPane: arrange the nodes in the pane horizontally from left to right
.(Default), or vertically from top to bottom, in the order in which they were added

MultipleStageDemo Run
259
FlowPane
You can specify the way the nodes placed either 
:by using
Orientation.HORIZONTAL: placed horizonatlly 
(default)
Orientation.VERTICAL: the nodes are placed 
.vertically
You can specify the gap between nodes in pixels 
if needed using setter and getter of attributes:
Hgap or vgap
FlowPane Attributes

Attributes of FlowPane class: alignment, 


orientation, hgap, vgap are binding
.properties

Each of which has set and get method. 


.setHgap(doble), getHgap(), etc
Insets, hGap, vGap
FlowPane_Layout Example
{ public class Lecture11 extends Application 
{ public void start(Stage primaryStage) 
 Scene scene = new Scene(root, 300, 250);
;Button[] b = new Button[5]  primaryStage.setTitle("Flow Layout");
for(int i=0; i< b.length; i++) 
primaryStage.setScene(scene);
primaryStage.show();
;b[i] = new Button("Button "+ i) 

}
;)(FlowPane root = new FlowPane 
root.setAlignment(Pos.CENTER);  public static void main(String[] args) {
//nodes are placed in center of GridPane launch(args);
;root.setHgap(6)  }
;root.setVgap(5) 
;root.getChildren().add(b[0])  } //End of class
;root.getChildren().add(b[1]) 
;root.getChildren().add(b[2]) 
;root.getChildren().add(b[3]) 
root.getChildren().add(b[4]); // or 
root.getChildren().addAll(b[0], b[1], 
;b[2],b[3],b[4])
FlowLayout-Example OutPut
Example(2)
{ public class Lecture11 extends Application 
{ public void start(Stage primaryStage) 
;)(Button btn = new Button 
;btn.setText("Say 'Hello World'") 
;Button btn2 = new Button("OK") 
;)(FlowPane root = new FlowPane 
root.getChildren().add(btn); //adding controls to Pane 
root.setHgap(5); //horizontal gap between each node is 5 pixels 
;root.getChildren().add(btn2) 
;Scene scene = new Scene(root, 300, 250) 
create a Scene window, place Pane in the scene// 
primaryStage.setTitle("First GUI"); //set stage title 
primaryStage.setScene(scene); // place Scene in the Stage 
primaryStage.show(); //display the Stage 

}
public static void main(String[] args) { launch(args); } 


;root.getChildren().add(btn2)
The getchildren() method returns an
instance of JavaDx List behaves similar to
ArrayList for storing a collection of
.elements

Invoking add( btn2): adds button into the


.list
GridPane: arranges nodes in a grid (matrix) formation. The nodes
.are placed in the specified column and row indices

ShowGridPane
Run

267
GridPane- Example
{ public class Lecture11 extends Application  root.add(b[0],0,0);
public void start(Stage primaryStage)  root.add(b[1],1,0); //col 1, row 0
{
root.add(b[2], 0,1);

root.add(b[3], 1,1);
;Button[] b = new Button[5] 
root.add(b[4], 0,2);

for(int i=0; i< b.length; i++) 

Scene scene = new Scene(root, 300, 250);
;b[i] = new Button("Button "+ i)
primaryStage.setTitle(“Grid Layout");

primaryStage.setScene(scene);
;)(GridPane root = new GridPane 
primaryStage.show();
;root.setAlignment(Pos.CENTER) 
}
nodes are placed in center of// 
GridPane
public static void main(String[] args) {
;root.setHgap(6) 
launch(args);
;root.setVgap(5)  }

 }
Output-GridLayout
BorderPane: can place nodes in five regions: top, bottom, left,
right and center, using the setTop(node), setBottom(node), setLeft(node),
setRight(node), and setCenter(node)

ShowBorderPane Run

270
BorderPane-Example
public class Lecture11 extends  root.setTop(b[0]);
{ Application root.setLeft(b[1]);
public void start(Stage  root.setRight(b[2]);
{ primaryStage) root.setCenter(b[3]);
;Button[] b = new Button[5]  root.setBottom(b[4]);
for(int i=0; i< b.length; i++) 
b[i] = new Button("Button "+  Scene scene = new Scene(root, 200, 250);
;i) primaryStage.setTitle(“Border Layout");
BorderPane root = new  primaryStage.setScene(scene);
;)(BorderPane primaryStage.show();
 }
;root.setAlignment(b[0],Pos.TOP_CENTER)
root.setAlignment(b[4],Pos.BOTTOM_CENT  public static void main(String[] args) {
;ER) launch(args);
 }

}
Output-Border Layout
Hbox: layout its children in a single
horizontal row

273
Vbox: layout its children in a single
vertical coloumn

ShowHBoxVBox Run

274
Frequently Used UI Controls

The following UI Controls are used frequently:


Label, Button, CheckBox, RadioButton, TextField, PasswordField, TextArea,
ComboBox, ListView, ScrollBar, and Slider.

275
Frequently Used UI Controls
Label TextField

CheckBox

Button
Radio Buttons
Labeled
A label is a display area for a short text, a node, or both.
It is often used to label other controls (usually text
fields). Labels and buttons share many common
properties. These common properties are defined in the
.Labeled class

:How to create
;Label lb = new Label("Hello there") 
)(Setting: To set the text on the label setText •
;lb.setText("Good Bye") 
)(Getting: To get the text from a label getText •
;)(String currentLabelStr = lb.getText 

277
ButtonBase and Button
A button is a control that triggers an action event when
clicked. JavaFX provides regular buttons, toggle
buttons, check box buttons, and radio buttons. The
common features of these buttons are defined in
.ButtonBase and Labeled classes
:How to create
Button offButton = new Button(); // without label 
Button onButton = new Button("Cancel"); //with label 

)(Setting: To set the label of a button setText


;offButton.setText("Press Me") 

)(Getting: To get the label of a button getText


;)(String offButtonLabel = offButton.getText 
278
TextField
A text field can be used to enter or display a string. TextField
.is a subclass of TextInputControl

:How to create by using different overloading constructors


TextField txfA = new TextField(); // empty textbox 
TextField txfC = new TextField("Type here"); // not empty 

)(Setting: To set the label of a button setText


;txfA.setText(“Type here") 
Setting: To set the width of text Field
;txfA.setPrefColumnCount(15) 

)(Getting: To get the label of a button getText


;)(String t = txfA.getText 
279
TextArea
.A TextArea enables the user to enter multiple lines of text

:How to create
TextArea ta = new TextArea ( ); // empty
;TextArea ta = new TextArea (“This is Text Area”)

Determine number of rows and columns


;ta. setPrefColumnCount(20)
;ta. setPrefRowCount(5)

Setting & Getting 


)(same as textbox setText(), getText 
:Wrapping
.As a default, text areas have 'word wrap' switched off
;ta.setWrapText(true) 
280
CheckBox
.They are used for the input of boolean value for a program 
They can either on or off 

:How to create • 
;CheckBox noviceUserType = new CheckBox("Novice") 
;CheckBox expeUserType = new CheckBox("Experienced") 

Getting: The state of a check box – whether or not it is on – can be • 


discovered by means of the method isSelected, which returns a
.boolean result true or false

;)(boolean b = expeUserType.isSelected 
RadioButton
Radio buttons, also known as option buttons, enable you to choose a
.single item from a group of choices
In appearance radio buttons resemble check boxes, but check boxes
display a square that is either checked or blank, whereas radio buttons
.display a circle that is either filled (if selected) or blank (if not selected)
:How to create
Create the buttons )1( //
;RadioButton fr = new RadioButton("French",) 
;RadioButton en = new RadioButton("English",) 
sn.setSelected(true); //initially selected 
Group the buttons )2( //
;)(ToggleGroup languageGroup = new ToggleGroup 
;fr.setToggleGroup(languageGroup) 
;en.setToggleGroup(languageGroup) 

Note: The aim of using a ToggleGroup object is to tell Java that a set of buttons 
are grouped together and have the property that only one of the buttons can be
selected at a time, that means the radio button that was selected previously
282
.becomes unselected
Event Driven Programming
Suppose you want to write a GUI
:program that
lets the user enter a loan amount,
annual interest rate, and number of
.years
then click the Compute Payment
button to obtain the monthly
.payment and total payment
?How do you accomplish the task
You have to use event-driven
programming to write the code to
LoanCalculator Run
respond to the button-clicking
.event
283
Procedural vs. Event-Driven
Programming

Procedural programming is executed in 


.procedural order

In event-driven programming, code is 


.executed upon activation of events

284
Events
An event can be defined as a type of
signal to the program that something
.has happened

The event is generated by external


user actions such as a button click,
mouse movements, mouse clicks, or
.keystrokes

285
Event Classes

286
Event Handler
To respond to a button click, you need to write the code 
to process the button-clicking action (what will be the
result if you press this button). There fore you have two
:members in this process
Event source object: where the object is originated that 
.fires an action such as clicking a button
The event handler or event listener object: which is an 
object that you create to handle the action event on a
.button, it contains a method for processing the event
Registering Handlers & Handling events
:An event handler object should do two things to handle an event 
You need to create a handler object as an instance of the .1
corresponding event-handler interface to ensure the handler has the
correct method for processing the event. JavaFx defines a unified
handler interface EventHandler<T extends Event> for an event T,
where T is a generic type that is a sub type of event. The handler
.interface contains the handle(T e) method for handling events
The handler object must be registered by the source object. .2
.Registration methods depend on the event type
 For an action event, the method setOnAction().
 For a mouse-pressed event, the method is
setOnMousePressed().
 For a keypressed event, the method is
setOnKeyPressed().
Selected User Actions and Handlers

289
Handling events

There are three ways to handle an event 


:using
Inner classes handler.1
Anonymous Inner-Class handlers.2
Using Lambda Expression.3
Inner Classes )1(
An inner class, or nested class, is a class 
.defined within a scope of another class
Inner classes are useful for defining 
.handler classes
Advantages: In some applications, you 
can use an inner class to make programs
.simple
.Inner Classes, cont

292
animation
Using Inner class to handle an event
public class HandleEvent extends Application {
public void start(Stage primaryStage) { 1. Start from the main
method to create a

window and display
OKHandlerClass handler1 = new OKHandlerClass();
it
btOK.setOnAction(handler1);
CancelHandlerClass handler2 = new CancelHandlerClass();
btCancel.setOnAction(handler2);

primaryStage.show(); // Display the stage
}
}

class OKHandlerClass implements EventHandler<ActionEvent> {


@Override
public void handle(ActionEvent e) {
System.out.println("OK button clicked");
}
}
293
293
animation
Trace Execution
public class HandleEvent extends Application {
public void start(Stage primaryStage) {

OKHandlerClass handler1 = new OKHandlerClass(); // create a handler object
btOK.setOnAction(handler1); // register handler object with the source object

CancelHandlerClass handler2 = new CancelHandlerClass();


2. Click OK
btCancel.setOnAction(handler2);

primaryStage.show(); // Display the stage
}
}

class OKHandlerClass implements EventHandler<ActionEvent> { //inner class


@Override
public void handle(ActionEvent e) {
System.out.println("OK button clicked");
}
294
} 294
animation
Trace Execution
public class HandleEvent extends Application {
public void start(Stage primaryStage) { 3. The JVM
… invokes the
OKHandlerClass handler1 = new OKHandlerClass(); listener’s handle
method
btOK.setOnAction(handler1);
CancelHandlerClass handler2 = new CancelHandlerClass();
btCancel.setOnAction(handler2);

primaryStage.show(); // Display the stage
}
}

class OKHandlerClass implements EventHandler<ActionEvent> {


@Override
public void handle(ActionEvent e) {
System.out.println("OK button clicked");
}
}
295
295
getSource() method

Instead of creating two different inner 


classes for two buttons, we can identify
the source of event using getSource()
.method
)(Using getSource
public class HandleEvent extends Application {
public void start(Stage primaryStage) {

HandlerClass handler1 = new HandlerClass();
btOK.setOnAction(handler1);
HandlerClass handler2 = new HandlerClass();
btCancel.setOnAction(handler2);

primaryStage.show(); // Display the stage
}

class HandlerClass implements EventHandler<ActionEvent> {


@Override
public void handle(ActionEvent e) {
if(e.getSource().equals(btOk))
System.out.println("OK button clicked");
else if( e.getSource().equals(btCancel))
…………….
}
}
}
Using Anonymous Inner Class to handle an )2(
event

An anonymous inner class is an inner 


class without a name. It combines defining
an inner class and creating an instance of
.the class into one step
:The syntax for anonymous inner class is 

new SuperClassName/InterfaceName() {
// Implement or override methods in superclass
or interface
// Other methods if necessary
}
Anonymous Inner Classes (cont.) )2(

AnonymousHandlerDemo Run
299
Anonymous Inner Classes (cont.) )2(
From previous example// 
{ )(>btOK.setOnAction( new EventHandler<ActionEvent 
{public void handle(Actionevent e) 
;System.out.println("OK button clicked") 
method // } 
event Handler // } 
argument// ;) 

You did registration and creation on one step // 


Simplifying Event Handing Using )3(
Lambda Expressions
Lambda expression is a new feature in Java 8. Lambda
expressions can be viewed as an anonymous method with a
.concise syntax
For example, the following code in (a) can be greatly simplified
.using a lambda expression in (b) in three lines

btEnlarge.setOnAction( btEnlarge.setOnAction(e -> {


new EventHandler<ActionEvent>() { // Code for processing event e
@Override });
public void handle(ActionEvent e) {
// Code for processing event e
}
}
});

(a) Anonymous inner class event handler (b) Lambda expression event handler
301
Lambda Expressions )3(
From previous example// 

(btOK.setOnAction 
e->{ System.out.println("OK 
button clicked"); }
;) 
Lambda Expression (cont.) )3(

The compiler treats a lambda expression as if it is an 


.object created from an anonymous inner class
The compiler processes a lambda expression in three 
:steps
1. Identify the lambda expression type
2. Identify the parameter types
3. Identify the statements
Exrexise(1)
Write a program to perform addition, 
subtraction, multiplication, and division as
.shown in figure below
Exercise(1) Solution
import javafx.application.Application; pane.getChildren().addAll(new Label("Number 1: "),
import javafx.geometry.*; tfNumber1, new Label("Number 2: "), tfNumber2,
import javafx.scene.*; new Label("Result: "), tfResult);
import javafx.scene.control.*;
import javafx.scene.layout.*; Button btAdd = new Button("Add");
import javafx.stage.Stage; Button btSubtract = new Button("Subtract");
Button btMultiply = new Button("Multiply");
public class Calculator extends Application { Button btDivide = new Button("Divide");

// Override the start method pane.getChildren().addAll(btAdd, btSubtract,


public void start(Stage primaryStage) { btMultiply, btDivide);
FlowPane pane = new FlowPane();
pane.setHgap(2); Scene scene = new Scene(pane, 250, 150);
pane.setVgap(5); primaryStage.setTitle("Calculator");
pane.setAlignment(Pos.CENTER); primaryStage.setScene(scene);
TextField tfNumber1 = new TextField(); primaryStage.show();
TextField tfNumber2 = new TextField();
TextField tfResult = new TextField();
tfResult.setEditable(false);
tfResult.setPrefColumnCount(15);
Exercise(1) Solution (Cont.)
btAdd.setOnAction(e -> {
tfResult.setText(Double.parseDouble(tfNumber1.getText()) +
Double.parseDouble(tfNumber2.getText()) + "");
});

btSubtract.setOnAction(e -> {
tfResult.setText(Double.parseDouble(tfNumber1.getText()) -
Double.parseDouble(tfNumber2.getText()) + "");
});
btMultiply.setOnAction(e -> {
tfResult.setText(Double.parseDouble(tfNumber1.getText()) *
Double.parseDouble(tfNumber2.getText()) + "");
});

btDivide.setOnAction(e -> {
tfResult.setText(Double.parseDouble(tfNumber1.getText()) /
Double.parseDouble(tfNumber2.getText()) + "");
});
}
public static void main(String[] args) {
launch(args);
}
} // end of class
The MouseEvent Class

MouseEventDemo Run

307
Event Registered Methods
The KeyEvent Class

KeyEventDemo Run

309
Shapes
JavaFX provides many shape classes for drawing texts,
lines, circles, rectangles, ellipses, arcs, polygons, and
polylines.

310
Text

311
Text Example

ShowText Run

312
Exampe Dragging a Text
;import javafx.application.Application  Scene scene = new Scene(pane, 300, 100);
;import javafx.scene.Scene 
;import javafx.scene.layout.Pane  primaryStage.setTitle("MouseEventDemo");
;*.import javafx.scene.text  primaryStage.setScene(scene);
 primaryStage.show();
;import javafx.stage.Stage
}
;*.import javafx.scene.paint 
{ public class Mouse extends Application  public static void main(String[] args) {
{ public void start(Stage primaryStage)  launch(args);
;)(Pane pane = new Pane  }
Text text = new Text(20, 20, "Programming is 
;fun") }
text1.setFont(Font.font("Courier", 
;FontWeight.BOLD, FontPosture.ITALIC, 15))
;text.setFill(Color.RED) 
;pane.getChildren().addAll(text) 
{ >- text.setOnMouseDragged(e 
;text.setX(e.getX()) 
;text.setY(e.getY()) 
;)} 

Line

ShowLine Run

314
Rectangle

315
Rectangle Example

ShowRectangle Run

316
Circle

317
Exercie(2): ControlCircle

Now let us consider to write a program that


.uses two buttons to control the size of a circle

ControlCircle Run

318
Controlcircle Solution
;import javafx.application.Application 
;import javafx.geometry.Pos 
;*.import javafx.scene 
;*.import javafx.scene.control 
;*.import javafx.scene.layout 
;*.import javafx.scene.shape 
;import javafx.stage.Stage 
;*.import javafx.scene.paint 
Controlcircle Solution(cont.)
public class Mouse extends Application {
public void start(Stage primaryStage) {

//create a Pane to hold circle


FlowPane pane = new FlowPane();
pane.setVgap(70);
Circle circle = new Circle(100,100,50);
circle.setStroke(Color.BLACK);
circle.setFill(Color.YELLOW); // you specify property, color, font, et before adding to pane
pane.getChildren().add(circle);

//create a Hbox Pane to hold Buttons


HBox hBox = new HBox();
hBox.setSpacing(10);
hBox.setAlignment(Pos.CENTER);
Button btEnlarge = new Button("Enlarge");
Button btShrink = new Button("Shrink");
hBox.getChildren().add(btEnlarge);
hBox.getChildren().add(btShrink);
Controlcircle Solution(cont.)
Create a BorderPane to inser Circe in center and Hbox pane at bottom // 
;)(BorderPane borderPane = new BorderPane 
;borderPane.setCenter(circle) 
;borderPane.setBottom(hBox) 
;BorderPane.setAlignment(hBox, Pos.CENTER) 
Handle events using Lambda Expression // 
;btEnlarge.setOnAction(e -> circle.setRadius(circle.getRadius() + 2)) 
;btShrink.setOnAction(e -> circle.setRadius(circle.getRadius() - 2)) 
.create Scene and stage// 
;Scene scene = new Scene(borderPane, 300, 300) 
;primaryStage.setTitle("Drawing a Circle") 
;primaryStage.setScene(scene) 
;)(primaryStage.show 
} 

public static void main(String[] args) { launch(args); } 


End of class // } 
Meeting 11: Recursion

Edited by: Dr. Bayan Abu Shawar


AOU-Jordan
Motivations

Suppose you want to find all the files under


a directory that contains a particular word.
How do you solve this problem? There are
several ways to solve this problem. An
intuitive solution is to use recursion by
searching the files in the subdirectories
.recursively

323
Motivations
H-trees, depicted in Figure below, are used in a very
large-scale integration (VLSI) design as a clock
distribution network for routing timing signals to all
parts of a chip with equal propagation delays. How do
you write a program to display H-trees? A good
.approach is to use recursion

324
Objectives
To describe what a recursive method is and the benefits of 
.using recursion
To develop recursive methods for recursive mathematical 
.functions
To explain how recursive method calls are handled in a call 
.stack
.To solve problems using recursion 
.To get the directory size using recursion 
. To solve the Tower of Hanoi problem using recursion 
.To draw fractals using recursion 
To discover the relationship and difference between recursion 
.and iteration

325
Recursive Algorithm

There are two approaches to writing 


:repetitive algorithms
Iterations: involves loops (while, and for)
Recursion: is a repetitive process in which
an algorithm call itself. Usually we write
recursion algorithm inside a method that
call itself several times till certain
.termination point happen
Characteristics of Recursion
:All recursive methods have the following characteristics

 One or more base cases (termination points) (the


simplest case) are used to stop recursion.
 Every recursive call reduces the original problem,
bringing it increasingly closer to a base case until
it becomes that case.

In general, to solve a problem using recursion, you


break it into subproblems. If a subproblem resembles
the original problem, you can apply the same approach
to solve the subproblem recursively. This subproblem is
almost the same as the original problem in nature with a
.smaller size
327
Computing Factorial

1, if n  0
Factorial (n)  
1 2  3  ..  (n  1)  n if n  1 otherwise

factorial(5) = 5 * 4* 3* 2* 1 =120 
Factorial(4)*5= 
Factorial(3)*4*5= 
Factorial(2)*3*4*5= 
Factorial(1)*2*3*4*5= 
factorial(0)*1*2*3*4*5= 
120>>>>>> 1*1*2*3*4*5= 
Approach 1: Iterative-Factorial

public static void main() {

int n = 5, fact = 1;

for(int i=2, i<=n; i++)


fact = fact * i;
System.out.println(“factorial of: “+ n+” = “+ fact);
}
The output:
Factorialof: 5 =120
Approach 2: Recursive Factorial
1, if n  0
Factorial (n)  
1 2  3  ..  (n  1)  n if n  1 otherwise

;factorial(0) = 1
;factorial(n) = n*factorial(n-1)

!n! = n * (n-1)
1 = !0
ComputeFactorial Run

330
Computing Factorial-Recursion
{ public static long factorial(int n) 
// Base case if (n == 0) 
;return 1 
else 
;return n * factorial(n - 1) 
} 
{ public static void main(String[] args) 
;Scanner input = new Scanner(System.in) 
;System.out.print("Enter a non-negative integer: ") 
;)(int n = input.nextInt 
System.out.println("Factorial of: " + n + " is " + 
;factorial(n))
} 
Computing Factorial
animation factorial(0) = 1;
factorial(n) = n*factorial(n-1);

factorial(4)

332
Computing Factorial
animation factorial(0) = 1;
factorial(n) = n*factorial(n-1);

factorial(4) = 4 * factorial(3)

333
Computing Factorial
animation factorial(0) = 1;
factorial(n) = n*factorial(n-1);

factorial(4) = 4 * factorial(3)
factorial(2) * 3 * 4 =

334
Computing Factorial
animation factorial(0) = 1;
factorial(n) = n*factorial(n-1);

factorial(4) = 4 * factorial(3)
) factorial(2) * 3 ( * 4 =
) )factorial(1) * 2( * 3( * 4 =

335
Computing Factorial
animation factorial(0) = 1;
factorial(n) = n*factorial(n-1);

factorial(4) = 4 * factorial(3)
factorial(2) * 3 * 4 =
)factorial(1) * 2( * 3 * 4 =
))factorial(0) * 1( * 2 ( * 3 * 4 =

336
Computing Factorial
animation factorial(0) = 1;
factorial(n) = n*factorial(n-1);

factorial(4) = 4 * factorial(3)
factorial(2) * 3 * 4 =
)factorial(1) * 2( * 3 * 4 =
))factorial(0) * 1( * 2 ( * 3 * 4 =
)))1 * 1 ( * 2 ( * 3 * 4 =

337
Computing Factorial
animation factorial(0) = 1;
factorial(n) = n*factorial(n-1);

factorial(4) = 4 * factorial(3)
factorial(2) * 3 * 4 =
)factorial(1) * 2( * 3 * 4 =
))factorial(0) * 1( * 2 ( * 3 * 4 =
)))1 * 1 ( * 2 ( * 3 * 4 =
)1 * 2 ( * 3 * 4 =

338
Computing Factorial
factorial(0) = 1;
animation
factorial(n) = n*factorial(n-1);

factorial(4) = 4 * factorial(3)
factorial(2) * 3 * 4 =
)factorial(1) * 2( * 3 * 4 =
))factorial(0) * 1( * 2 ( * 3 * 4 =
)))1 * 1 ( * 2 ( * 3 * 4 =
)1 * 2 ( * 3 * 4 =
2*3*4=

339
Computing Factorial
factorial(0) = 1;
animation
factorial(n) = n*factorial(n-1);

factorial(4) = 4 * factorial(3)
)factorial(2) * 3( * 4 =
))factorial(1) * 2( * 3( * 4 =
)))factorial(0) * 1( * 2 ( * 3( * 4 =
))))1 * 1 ( * 2 ( * 3( * 4 =
))1 * 2 ( * 3( * 4 =
)2 * 3( * 4 =
)6 ( * 4 =
340
Computing Factorial
animation factorial(0) = 1;
factorial(n) = n*factorial(n-1);

factorial(4) = 4 * factorial(3)
)factorial(2) * 3( * 4 =
))factorial(1) * 2( * 3( * 4 =
)))factorial(0) * 1( * 2 ( * 3( * 4 =
))))1 * 1 ( * 2 ( * 3( * 4 =
))1 * 2 ( * 3( * 4 =
)2 * 3( * 4 =
)6( * 4 =
341 24 =
Trace Recursive factorial
Executes factorial(4)
animation

factorial(4)
Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes factorial(3)
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2 Stack

return 2 * factorial(1)
Step 3: executes factorial(1)
Step 6: return 1
return 1 * factorial(0)
Step 4: executes factorial(0)
Step 5: return 1 Space Required
for factorial(4)
return 1 Main method

342
Trace Recursive factorial
animation

factorial(4)
Step 0: executes factorial(4)
Step 9: return 24 Executes factorial(3)
return 4 * factorial(3)
Step 1: executes factorial(3)
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2 Stack

return 2 * factorial(1)
Step 3: executes factorial(1)
Step 6: return 1
return 1 * factorial(0) Space Required
for factorial(3)
Step 4: executes factorial(0)
Step 5: return 1 Space Required
for factorial(4)

return 1 Main method

343
Trace Recursive factorial
animation

factorial(4) Executes factorial(2)


Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes factorial(3)
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2
Stack
return 2 * factorial(1)
Step 3: executes factorial(1)
Step 6: return 1
Space Required
return 1 * factorial(0) for factorial(2)
Space Required
Step 4: executes factorial(0) for factorial(3)
Step 5: return 1 Space Required
for factorial(4)
return 1 Main method

344
Trace Recursive factorial
animation

factorial(4) Executes factorial(1)


Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes factorial(3)
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2 Stack

return 2 * factorial(1)
Space Required
Step 3: executes factorial(1) for factorial(1)
Step 6: return 1 Space Required
for factorial(2)
return 1 * factorial(0) Space Required
for factorial(3)
Step 4: executes factorial(0)
Step 5: return 1 Space Required
for factorial(4)
return 1 Main method

345
Trace Recursive factorial
animation

factorial(4) Executes factorial(0)


Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes factorial(3)
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2 Stack

return 2 * factorial(1) Space Required


for factorial(0)
Space Required
Step 3: executes factorial(1) for factorial(1)
Step 6: return 1 Space Required
for factorial(2)
return 1 * factorial(0) Space Required
for factorial(3)
Step 4: executes factorial(0)
Step 5: return 1 Space Required
for factorial(4)
return 1 Main method

346
Trace Recursive factorial
animation

factorial(4) returns 1
Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes factorial(3)
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2 Stack

return 2 * factorial(1) Space Required


for factorial(0)
Space Required
Step 3: executes factorial(1)
Step 6: return 1 for factorial(1)
Space Required
for factorial(2)
return 1 * factorial(0)
Space Required
Step 4: executes factorial(0) for factorial(3)
Step 5: return 1 Space Required
for factorial(4)
return 1 Main method

347
Trace Recursive factorial
animation

factorial(4) returns factorial(0)


Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes factorial(3)
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2 Stack

return 2 * factorial(1) Space Required


for factorial(0)
Space Required
Step 3: executes factorial(1)
Step 6: return 1 for factorial(1)
Space Required
for factorial(2)
return 1 * factorial(0)
Space Required
Step 4: executes factorial(0) for factorial(3)
Step 5: return 1 Space Required
for factorial(4)
return 1 Main method

348
Trace Recursive factorial
animation

factorial(4) returns factorial(1)


Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes factorial(3)
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2
Stack
return 2 * factorial(1)
Step 3: executes factorial(1)
Step 6: return 1 Space Required
for factorial(1)

return 1 * factorial(0) Space Required


for factorial(2)
Step 4: executes factorial(0) Space Required
Step 5: return 1 for factorial(3)
Space Required
return 1 for factorial(4)
Main method

349
Trace Recursive factorial
animation

factorial(4) returns factorial(2)


Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes factorial(3)
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2
Stack
return 2 * factorial(1)
Step 3: executes factorial(1)
Step 6: return 1
return 1 * factorial(0) Space Required
for factorial(2)

Step 4: executes factorial(0) Space Required


Step 5: return 1 for factorial(3)
Space Required
return 1 for factorial(4)
Main method

350
Trace Recursive factorial
animation

factorial(4) returns factorial(3)


Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes factorial(3)
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2
Stack
return 2 * factorial(1)
Step 3: executes factorial(1)
Step 6: return 1
return 1 * factorial(0)
Step 4: executes factorial(0) Space Required
Step 5: return 1 for factorial(3)
Space Required
return 1 for factorial(4)
Main method

351
Trace Recursive factorial
animation
returns factorial(4)

factorial(4)
Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes factorial(3)
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2 Stack

return 2 * factorial(1)
Step 3: executes factorial(1)
Step 6: return 1
return 1 * factorial(0)
Step 4: executes factorial(0)
Step 5: return 1 Space Required
for factorial(4)
return 1 Main method

352
factorial(4) Stack Trace
5 Space Required
for factorial(0)

4 Space Required
for factorial(1)
Space Required
for factorial(1)

3 Space Required
for factorial(2)
Space Required
for factorial(2)
Space Required
for factorial(2)

2 Space Required
for factorial(3)
Space Required
for factorial(3)
Space Required
for factorial(3)
Space Required
for factorial(3)

1 Space Required
for factorial(4)
Space Required
for factorial(4)
Space Required
for factorial(4)
Space Required
for factorial(4)
Space Required
for factorial(4)

6 Space Required
for factorial(1)
Space Required
for factorial(2)
7 Space Required
for factorial(2)
Space Required Space Required 8 Space Required
for factorial(3) for factorial(3) for factorial(3)
Space Required Space Required Space Required
for factorial(4) for factorial(4) for factorial(4)
9 Space Required
for factorial(4)

353
Other Examples
Assume the below method: What will be the out of f(5)?
f(0) = 0;
f(n) = n+ f(n-1); f(5) = 5+ f(4)
Java method//
4 + f(3)
{public static int f (int n)
3 + f(2)
2 + f(1)
if (n==0)
1 + f(0)
return 0 0
else
;return n+f(n-1)
F(5) = 5+4+3+2+1+0 = 15
}

354
Fibonacci Numbers
…Fibonacci series: 0 1 1 2 3 5 8 13 21 34 55 89
indices: 0 1 2 3 4 5 6 7 8 9 10 11
The series starts by 0, 1 then each element is the summation of the previous two
.elements

;fib(0) = 0
;fib(1) = 1
fib(index) = fib(index -1) + fib(index -2); index >=2

fib(3) = fib(2) + fib(1) = (fib(1) + fib(0)) + fib(1) = (1 + 0)


+fib(1) = 1 + fib(1) = 1 + 1 = 2
ComputeFibonacci Run
355
Solution of Fibonacci Series
public static int fibRecursive (int n)
{ if(n ==0)
return 0;
else if( n==1)
return 1;
else
return fibRecursive(n-1)+fibRecursive(n-2);
}
{ public static int fibIterative(int n) 
;int i=0,result=1,prevresult=0 
{while(i<n-1) 
;int temp=result 
;result=result+prevresult 
;++prevresult=temp; i 
} 
;return result 
} 
.Fibonnaci Numbers, cont
fib(4)
17: return fib(4) 0: call fib(4)

return fib(3) + fib(2)


11: call fib(2)
10: return fib(3)

1: call fib(3) 16: return fib(2)

return fib(2) + fib(1) return fib(1) + fib(0)


7: return fib(2) 8: call fib(1) 14: return fib(0)
2: call fib(2) 13: return fib(1) 12: call fib(1)

9: return fib(1) 15: return fib(0)


return fib(1) + fib(0) return 1 return 1 return 0
4: return fib(1) 5: call fib(0)

3: call fib(1)

return 1 6: return fib(0) return 0

357
Problem Solving Using Recursion
Let us consider a simple problem of printing a message
for n times. You can break the problem into two
subproblems: one is to print the message one time and
the other is to print the message for n-1 times. The
second problem is the same as the original problem
with a smaller size. The base case for the problem is
n==0. You can solve this problem using recursion as
:follows
;nPrintln(“Welcome”, 5)
public static void nPrintln( String message, int times) {
if (times >= 1) {
System.out.println(message);
nPrintln(message, times - 1);
} // The base case is times == 0
} 358
Think Recursively
Many of the problems presented in the early
chapters can be solved using recursion if you
think recursively. For example, the palindrome
:problem can be solved recursively as follows
public static boolean isPalindrome(String s) {
if (s.length() <= 1) // Base case
return true;
else if (s.charAt(0) != s.charAt(s.length() - 1)) // Base case
return false;
else
return isPalindrome(s.substring(1, s.length() - 1)); }
Mlkklm >>> lkkl >>>> KK >>> true it is palindrome
mlkHlm >>>> lkHl >>> kH >> False it is not palindrome
359
Directory Size
The preceding examples can easily be solved without
using recursion. This section presents a problem that
is difficult to solve without using recursion. The
problem is to find the size of a directory. The size of a
directory is the sum of the sizes of all files in the
directory. A directory may contain subdirectories.
Suppose a directory contains files , , ..., , and
.subdirectories , , ..., , as shown below

directory

f1 f2 ... fm d1 d2 dn
...
1 1 1 1 1 1
360
Directory Size
The size of the directory can be defined
:recursively as follows
size( d )  size( f1 )  size( f 2 )  ...  size( f m )  size( d1 )  size( d 2 )  ...  size( d n )

DirectorySize Run

361
Directory size Solution
{ public static long getSize(File file) 
long size = 0; // Store the total size of all files 
if (file.isDirectory()) 
{ 
File[] files = file.listFiles(); // All files and subdirectories 
for (int i = 0; files != null && i < files.length; i++) 
size += getSize(files[i]); // Recursive call 
} 
else 
Base case // 
;)(size += file.length 
;return size 
} 
Tower of Hanoi
The problem involves moving a special number of 
disks of distinct sizes from one tower to another while
:observing the following rules
 There are n disks labeled 1, 2, 3, . . ., n, and three
towers labeled A, B, and C.
 No disk can be on top of a smaller disk at any time.
 All the disks are initially placed on tower A.
 Only one disk can be moved at a time, and it must
be the top disk on the tower.

363
.Tower of Hanoi, cont
The objective
of the problem
is:
to move all
the disks from
A to B with
the assistance
of C

364
Solution to Tower of Hanoi
.The Tower of Hanoi problem can be decomposed into three subproblems

365
Solution to Tower of Hanoi

Move the first n - 1 disks from A to C with the 


.assistance of tower B
.Move disk n from A to B 
Move n - 1 disks from C to B with the assistance of 
.tower A

TowerOfHanoi Run

366
Solution of Tower of Hanoi Problem
https://www.cs.cmu.edu/~cburch/survey/recurse/hanoiex.html

{ public static void main(String[] args) 


;Scanner input = new Scanner(System.in) 
;System.out.print("Enter number of disks: ") 
;)(int n = input.nextInt 
;System.out.println("The moves are:") 
;moveDisks(n, 'A', 'B', 'C') 
}
Solution of Tower of Hanoi Problem
public static void moveDisks(int n, char fromT, char toT, char auxT) 
{
if (n == 1) 

;System.out.println("Move disk " + n + " from " + fromT+ " to " + toT) 

{ else 

;moveDisks(n - 1, fromT, auxT, toT) 

;System.out.println("Move disk " + n + " from " + fromT+ " to " + toT) 

;moveDisks(n - 1, auxT, toT, fromT) 

} 

}
Trace Tower of Hanoi Program
moveDisks(3, ’A’, ’B’, ’C’)
Exercise 18.3 GCD

gcd(2, 3) = 1
gcd(2, 10) = 2
gcd(25, 35) = 5
gcd(205, 301) = 5
gcd(m, n)

Approach 1: Brute-force, start from min(n, m) down 


to 1, to check if a number is common divisor for both
.m and n, if so, it is the greatest common divisor
Approach 2: Euclid’s algorithm 
Approach 3: Recursive method 
370
Approach 2: Euclid’s algorithm
;Get absolute value of m and n //
;t1 = Math.abs(m); t2 = Math.abs(n)
;r is the remainder of t1 divided by t2 //
;r = t1 % t2
{ while (r != 0)
;t1 = t2
;t2 = r
;r = t1 % t2
}
 
When r is 0, t2 is the greatest common //
divisor between t1 and t2 //
;return t2
371
Approach 3: Recursive Method

;gcd(m, n) = n if m % n = 0
;gcd(m, n) = gcd(n, m % n); otherwise

//Java method
public static int gcd(int m, int n){
if (m%n==0)
return n;
else
return gcd(n, m%n);
}

372
?Fractals

A fractal is a geometrical figure just like


triangles, circles, and rectangles, but fractals
can be divided into parts, each of which is a
.reduced-size copy of the whole

There are many interesting examples of


fractals. This section introduces a simple fractal,
called Sierpinski triangle, named after a famous
.Polish mathematician

373
Sierpinski Triangle
It begins with an equilateral triangle, which is considered to be the .1
.Sierpinski fractal of order (or level) 0, as shown in Figure (a)
Connect the midpoints of the sides of the triangle of order 0 to .2
.create a Sierpinski triangle of order 1, as shown in Figure (b)
Leave the center triangle intact. Connect the midpoints of the sides .3
of the three other triangles to create a Sierpinski of order 2, as
.shown in Figure (c)
You can repeat the same process recursively to create a Sierpinski .4
.triangle of order 3, 4, ..., and so on, as shown in Figure (d)
You can try next example after fishing meeting 11 and 12 (by your .5
own)

374
Sierpinski Triangle Solution
SierpinskiTriangle

Run

375
Recursion vs. Iteration
Recursion is an alternative form of program control.
.It is essentially repetition without a loop

Recursion bears substantial overhead. Each time


the program calls a method, the system must
assign space for all of the method’s local variables
and parameters. This can consume considerable
memory and requires extra time to manage the
additional space.

376
Advantages of Using Recursion

Recursion is good for solving the problems that


are inherently recursive.

377
Meeting 13: Sets and Maps

Edited by: Dr. Bayan Abu Shawar


AOU-Jordan
Objectives

.To store unordered, non-duplicate elements using a set 

To explore how and when to use HashSet, LinkedHashSet, or 


.TreeSet to store elements

.To compare performance of sets and lists 

To tell the differences between Collection and Map and describe 


when and how to use HashMap, LinkedHashMap, and TreeMap
.to store values associated with keys

379
Motivations
The “No-Fly” list is a list, created and maintained by the
U.S. government’s Terrorist Screening Center, of people
who are not permitted to board a commercial aircraft for
travel in or out of the United States. Suppose we need to
write a program that checks whether a person is on the
No-Fly list. You can use a list to store names in the No-
Fly list. However, a more efficient data structure for this
.application is a set
Suppose your program also needs to store detailed information
about terrorists in the No-Fly list. The detailed information
such as gender, height, weight, and nationality can be retrieved
using the name as the key. A map is an efficient data structure
for such a task.
380
The Collection FrameWork

The Collections Framework unifies the


collection classes. It contains two root
.interfaces, Collection and Map
Set, List, and Queue is a subinterface of
.Collection
Arrays are not part of the Collections
Framework, as they do not implement
.either the Collection or Map interfaces
Collection FrameWork
Review of Java Collection
Framework hierarchy
.Set and List are subinterfaces of Collection

383
The Collection interfaces
The Collection interface is the root interface for 
manipulating a collection of objects: Set, List,
.Queue
:The Collections Framework does three things 
 It specifies a set of collection interfaces
 recommends some constructors for the classes that
implement them;
 provides some utility classes.
These, together with collection classes meeting 
these specifications are said to constitute the
.Collections Framework
An Interface

As you studied before, an interface is 


essentially a list of methods without any actual
implementation/ abstracted and final
.variables
Any concrete class that implements an 
interface must (overriding) understand all the
messages associated with the methods in the
interface, either by implementing the methods
.or inheriting them from a superclass
Collection Interface
The Collection interface is a superinterface of the 
.collection interfaces: Set, List, and Queue 
All of the methods in Collection are inherited by the 
.interfaces Set, List, Queue, etc
The Collection interface specifies methods such as 
add(), size() and isEmpty(), which are common to very
.many kinds of collection

:In order to use any Collection type, You need to 


import java.util.*;
387
ArrayList
?How can we print the contents of the arrayList 
;)(>ArrayList <String> list1= new ArrayList<String 
;list1.add(“malak”); list1.add(“lolo”) 
print them on screen // 
;System.out.println(list1) 

for (int i=0; i<list1.size(); i++) 


};System.out.println(list1.get(i)) 

for ( String x : list 1) 


;System.out.println(x) 
Iterator-Interface
This interface allows traversing / iterating through any collection, 
.such as Set, an ArrayList, etc

The following abstract methods are defined for any class that 
:implements the iterator

boolean hasNext(): returns true if the iteration has more elements 

E next(): returns the next element in the iteration(E is the type the 
interface is implemented for)

void remove() : removes from the underlying collection the last 


element returned by the iterator; note that it is important to precede
.)(any call to remove() by a call to next
Iterator Interface
.Note that it is possible to declare a variable of an interface type 
any class that implements the Iterator interface may be referenced by such 
.a variable

;)(>ArrayList<String> X = new ArrayList<String 


;X.add(“mlk”); X.add(“lolo”) 
........ 
;)(Iterator<String> listX = X.iterator 

while (listX.hasNext()) 
;System.out.print( listX.next() + " , ") 
, Mlk , lolo 
Some of Collection Interface
Methods
The Set Interface
A set is a not ordered collection in which every element 
.is unique (i.e. there are no duplicates)
A set can grow and shrink as elements are added or 
.removed (dynamic size)
The contents of a set are not indexed, so we have no 
way of reaching a particular item except by stepping
.through the elements until we come to the one we want
The most general kind of set is unordered, although we will see that 
.ordered sets also exist 
You should think of a set as a pool of objects, none of which can 
appear twice, and we can add things to the pool or remove them as
.we please
The Set Interface
The Set interface extends the Collection
.interface
It does not introduce new methods or
constants, but it stipulates that an instance of Set
.contains no duplicate elements
The concrete class that implements Set must
ensure that no duplicate elements can be added
.to the set
That is NO two elements e1 and e2 can be in
the set such that e1.equals(e2) is true.no
393
duplicate
The Set Interface
Hierarchy

394
Creating a Set
Whenever we use any kind of collection from the Java Collections 
:Framework there are three things we must do first 

Decide on the interface type. What protocol do we want to use with .1


our collection? Interface Set

Choose an implementation class. That is, what class will the actual .2
collection belong to? Implementation class: HashSet

Declare an element type. What data type will the collection contain? .3
A set of String, Integer, Doubles, etc, the element type should be a
.reference type not primitive the same as ArrayList

Wrapper classes .4
HasheSet, TreeSet, &
LinkedHashSet
You can declare an object of 
Set<Element_Type> collection, and create
:it using any of the below concrete classes
 HashSet doesn’t maintain any kind of order of its
elements and unique.
 TreeSet sorts the elements in ascending order and
unique .
 LinkedHashSet maintains the insertion order and
unique.
Declaring and creating a variable to reference a
set for holding strings
Class object = new Constrcutor();
;)( >Interface <E> nameobject = new Constructor <E
Declaration

Creation
Decaring and Creatng a Set
Collection
;)(>Collection Interface<E> name = new CocreteClass<E 

Set <String> set1 = new HashSet <String>(); OR 

;)( >HashSet<String> set1 = new HashSet <String 


capacity
;Set <Double> set2 = new HashSet <Double> (10) 

;Set<String> Set3 = new HashSet <String>(set1)


Another

collection
The above statement will copy set1 to set3// 

Set <String> set4 = new TreeSet<String>(set1); <<< Ordered and unique 

.set4 will have the same content of set3 but in ascending order// 
The HashSet Class
The HashSet class is a concrete class that
.implements Set
For efficiency, objects added to a hash set
need to implement the hashCode method in
a manner that properly disperses the hash
.code
)( >HashSet <E
HashSet <E> (c: Collection<E>)
399
The SortedSet Interface and the
TreeSet Class
SortedSet is a subinterface of Set, which
guarantees that the elements in the set are sorted –
. ascending
TreeSet is a concrete class that implements the
SortedSet interface. You can use an iterator to
.traverse the elements in the sorted order
)( >TreeSet <E
TreeSet <E> (c: Collection<E>)

400
LinkedHashSet Class

LinkedHashSet maintains the insertion 


order. Elements gets sorted in the same
sequence in which they have been added
to the Set. Unordered and unique
;)(>LinkedHashSet<E
;LinkedHashSet<E>(c: Collection<E>)
Some of the methods specified by
the Set interface
Iterating over a Set

:You can iterate over a Set using 


For-each statement

Using iterator
For-each statement
{ public static void main(String[] args) 
Create a hash set // 
;)( >Set <String> set = new HashSet <String 
Add strings to the set // 
set.add("London"); set.add("Paris"); set.add("New York"); 
;set.add("San Francisco"); set.add("Beijing")
set.add("New York"); // <<<<<<<<<< not added 
;System.out.println(set) 
Display the elements in the hash set // 
for (String s: set) 
;System.out.print(s.toUpperCase() + " ") 
System.out.print(“Size = ”+ set.size() ); >>>> Size = 5 
} 
Exercise(1)

:Write Java code to do the followings 


Create a set of strings with each element
.being the name of a herb
Add the following herbs: Rosemary,
.Parsely, Camomile, Rosemary
Print out the size of the set
Print the set
Solution of Exercise(1)
;)(>Set<String> herbSet = new HashSet<String 
;herbSet.add("Rosemary") 
;herbSet.add("Parsely") 
;herbSet.add(“Camomile") 
;herbSet.add("Rosemary") 
;System.out.println(herbSet.size()) 
;System.out.println(herbSet) 
3
]Rosemary, Parsly, Camomile[ 
TreeSet Class
Suppose we wanted to have the herbs printed 
out alphabetically. In this case you need to use
.TreeSet, which does have order
All we need to do is alter 
Set<String> set = new HashSet<String>();
to 
Set<String> set = new TreeSet<String>();

.The herbs will now automatically be in order 


Case Study: Counting Keywords

This section presents an application that


counts the number of the keywords in a Java
.source file

CountKeywords Run

408
Bulk Operations on Set Interface
The interface Set defines several useful bulk operations; that is, 
operations that involve every element in one or more sets. Below
are some of the bulk Operations : Let us assume that set1 and set2
.reference instances of classes that implement Set
;set1.containsAll(set2) 
.Answers true if set1 contains all the elements in set2 
set1.addAll(set2); //set1 = set1 Union set2 
Adds all of the elements in set2 to set1, if they are not already present, 
answering true if set1 was altered. Union between two sets
set1.retainAll(set2); set1 = set1 intersect set2 
Retains any elements set1 has in common with set2, answering true if set1 
was changed. Intersection between two sets
set1.removeAll(set2); //set1 = set1 – set2 
Removes any elements from set1 that set1 has in common with set2, 
answering true if set1 was changed. Set difference
Bulk Operations on Set Interface
Operations that alter the contents of the receiver are 
referred to as destructive operations, whereas those that
.do not are referred to as nondestructive operations

The bulk methods retainAll(), addAll() and removeAll() 


correspond to the set operations known as intersection,
union and set difference. These methods are destructive
– they alter the original set – so it is normally best to
.work with a copy
Exercise(2)

Create two linked Hash sets 


and {2,3,7,8,9} . <<<Arrays ,}3,4,5,2,1{ 
Find and print their union, intersection, and 
difference. You need to print the original
.sets first
Solution of Exercise(2)
{ public static void main(String[] args) 
;Integer[] a1 = {3,4,5,2,1} 
;Integer[] a2 = {2,3,7,8,9} 
;List<Integer> l1 = new ArrayList<Integer>(Arrays.asList(a1)) 
;List<Integer> l2 = new ArrayList<Integer>(Arrays.asList(a2)) 

;Set<Integer> s1 = new LinkedHashSet<Integer>(l1) 
;Set<Integer> s2 = new LinkedHashSet<Integer>(l2) 

;Set<Integer> union = new LinkedHashSet<Integer>(s1) 
;Set<Integer> intersect = new LinkedHashSet<Integer>(s1) 
;Set<Integer> difference = new LinkedHashSet<Integer>(s1) 

;System.out.println("s1: "+ s1) 
;System.out.println("s2: "+ s2) 
;difference.removeAll(s2) 
;System.out.println("s1-s2 = "+ difference) 
;union.addAll(s2) 
;System.out.println("s1 union s2 = "+ union) 
;intersect.retainAll(s2) 
;System.out.println("s1 intersects s2 = "+ intersect) 
} 
Map Interface

A Map Interface stores pairs of linked


items in key–value pairs known as entries.
It looks like a table wherein the key should
.be unique

Maps are dynamically sized, indexed by


keys and do not allow duplicate keys. The
.elements are unordered
The Map Interface
The Map interface maps keys to the elements. The
keys are like indexes. In List, the indexes are
.integer. In Map, the keys can be any objects

414
Map Interface and Class Hierarchy

An instance of Map represents a group of objects,


each of which is represented as key-value. You can
get the object from a map using a key, and you
.have to use a key to put the object into the map

415
The Map Interface UML Diagram

416
Some of the Methods of the Map Interface
Concrete Map Classes

418
Concrete classes to implement Map
Interface
There are three concrete classes that 
:implements Map interface
HashMap:  is implemented as a hash table, and
there is no ordering on keys or values.
TreeMap: is implemented based on red-black
tree structure, and it is ordered by the key. 
LinkedHashMap: inherits HashMap, and is
implemented as linked list that maintains the
insertion order.
Declare and create a Map
?How to declare a HashMap 
Similar to ArrayList, and Set but with the types of both 
.the key and value
Map <String,String> table1 = new HashMap <String,String> (); OR 

;)( >HashMap <String,String> table1 = new HashMap <String,String 

;Map <String,Double> table2 = new HashMap <String,Double> (10) 


Capacity

;Map <String,String> table3 = new HashMap <String,String> (table1) 


Another Map

The above statement will copy table1 to table 3// 

;Map <String,String> table4 = new TreeMap <String,String>(table1) 

table4 will have the same content of able 3 but in ascending order// 
.based on the key
Traversing Map Collection
You can use for each statement to iterate 
.a Map row by row
For(Key_Type variable: Map_Name.keySet()){
//the key is stored in variable, to obtain the value use
//Map_name.get(variable)
}
:Example 
;)( >Map <String, String> table1 = new HashMap <String,String 
for( String key : table1 . keySet()) 
;System.out.println(key+” “+ table1.get(key) ) 
Exercise(3): Using HashMap and
TreeMap
This exercise creates a hash map that maps names to their
.ages
The program first creates a hash map with the name as its key and
age as its value: (“Smith”,30), (“Anderson", 31), (“Lewis", 29), and
("Cook", 29). Then display the content.
Print out the names whose age are greater than or equal to 30.
Print out the age of Lewis
The program then creates a tree map from the hash map, and
displays the mappings in ascending order of the keys.

TestMap Run
422
Exercise(3)_Solution
public class TestMap {
public static void main(String[] args) {
// Create a HashMap
Map<String, Integer> hashMap = new HashMap<String, Integer>();
hashMap.put("Smith", 30); hashMap.put("Anderson", 31);
hashMap.put("Lewis", 29); hashMap.put("Cook", 29);

System.out.println("Display entries in HashMap");


System.out.println(hashMap + "\n"); { ( , ) , ( ,) }
System.out.println("\nThe age for " + "Lewis is " + hashMap.get("Lewis"));
System.out.println("Names for those whose ag >= 30 are: ");
for(String key: hashMap.keySet())
if(hashMap.get(key) >= 30)
System.out.println(s+" "+ hashMap.get(key));
Continue-Exercise(3)_Solution

// Create a TreeMap from the preceding HashMap

Map <String, Integer> treeMap = new TreeMap<String, Integer>(hashMap);

System.out.println("Display entries in ascending order of key");

System.out.println(treeMap);

}
}// end class
Exercise(4): Counting the Occurrences of
Words in a String
Write Java program to count the occurrences of words
in a text and displays the words and their occurrences in
:ascending order of the words. Assume text is
Good morning. Have a good class. " + "Have a good"
"!visit. Have fun
The program uses a hash map to store a pair
consisting of a word and its count. For each word, check
whether it is already a key in the map. If not, add the key
and value 1 to the map. Otherwise, increase the value
.for the word (key) by 1 in the map
.Display the content of the Map
CountOccurrenceOfWords Run
425
Solution of Exercise(4)
;*.import java.util 
{ public class CountOccurrenceOfWords 
{ public static void main(String[] args) 
;"!String text = "Good morning. Have a good class. " + "Have a good visit. Have fun 
;)(>Map<String, Integer> map = new TreeMap<String, Integer 
String[] words = text.split("\\W+"); // split text into words , this mean the 
.delimiter will be anything that is not a word
{ for (int i = 0; i < words.length; i++) 
;)(String key = words[i].toLowerCase 
{ if (key.length() > 0) 
if (!map.containsKey(key)) 
;map.put(key, 1) 
{ else 
;int value = map.get(key) 
;++value 
} ;map.put(key, value) 
} 
for// } 
Continue Solution of Exercise(4)

;System.out.println(“Words \t Count”) 
;)”----------------------------“(System.out.println 
for(String t : map.keySet()) 
;System.out.println(t+”\t“+ map.get(t)) 

main//} 
class//} 
Important Notes
The Collection Framework has two rooted interfaces: 
.Collection, and Map
Set, List, and Queue are sub-Interfaces from Collection 
.Interface
Distinguish between Collection Interface, and the 
Collections class that is used to do some operations on
the ArrayList such as: reverse, sort, etc as you studied in
.Meeting6
You did not use Collection Interface methods directly, 
you use its sub-Interfaces to declare objects of Set, List,
or Queue then use objects to invoke methods. Wherein
Collections class methods are used using Collections
.class to invoke methods: Collections.sort(x), etc
Meeting 14: Threads

Edited by: Dr. Bayan Abu Shawar


AOU-Jordan
Objectives
 Introduction to Threads

 Creating threads in Java

 Thread states

430
Threads in Java
Java is a Threaded language which allows a program to do several things at 
.once

Threads are separate activities within a program, each of which has a beginning 
.and an end
Example: You might want to monitor the keyboard for a key being pressed by a – 
user and, at the same time, track the movement of the mouse by the user and
repaint the screen. Each of these tasks/activities can be thought of as a single
.thread in one program
The Java system has a component known as the scheduler that makes 
.decisions about which thread to run next

Threads are not the actual static code itself but rather they are the dynamic 
process of executing that code

So far, all of the programs that you have written have had only one thread and 
.this has been the thread started by the main method
Introduction

• Concurrent systems
– It is an area of computer science that represents the concepts surrounding
the use of threads.
– a concurrent system consists of a collection of separate activities or tasks
that are simultaneously at some stage between their starting and finishing
point.

• In a concurrent system, each task is made into a thread and …


– on a multiprocessor computer, each thread can truly run at the same time as
all of the other threads (up to the number of processors available, of course).
– on a single-processor computer, the CPU can carry out only one set of
instructions at a time. In this situation the threads share the CPU, and the
operating system will allocate small blocks of time to each thread.

43
2
Creating Threads
• A thread is treated as an object in Java and the Thread class is found
in the java.lang library. <<< no import is needed
– The Thread class has a number of methods for creating, destroying and
modifying threads.
• Threaded classes can be defined in two ways:

(1) by inheriting from the Thread class


• This method is used if you wish to inherit from only one class,
the Thread class.
• Note that Java does not allow multiple inheritance

(2) or by implementing the Runnable interface.


• Defining threads by implementing the Runnable interface is
used when you want to inherent from a class other than the
Thread class.

43
3
Creating Threads
2.1 Inheriting from the Thread class
•The general approach is
(1) Define a class by extending the Thread class and overriding the run
method.
• In the run method, you should write the code that you wish to run when this
particular thread has started running state.
(2) Create an instance object of the above class
(3) Start running the instance using the start() method that is defined
in Thread.
Exampl The output

e

434
Creating Threads
2.2 Implementing the Runnable interface
•The general approach is
(1) Define a class that implements Runnable and overriding the run
(2) Create an instance object of the above class. method
(3) Create a thread that runs this instance. .
(4) Start running the instance using the start method.
Exampl The output
e

435
Creating Threads
2.3 Thread states
•We need to look at the various
states that a thread can be in and
how a thread might move from
one state to another.
•A thread is in one of five states
at any moment in time:
(1) initial state;
(2) runnable state;
(3) running state;
(4) blocked state;
(5) finished state.

The figure shows the possible


transitions between states.

43
6
Movement from one state to another is governed by:
(1)a number of methods from Thread class and the Object
class
(2)the operating system and other external factors.
Note the following in the figure:
•A thread is put into the initial state by means of it being
created using new.
•Thread t1= new Thread(); <<< it is in initial state
•Thread is a class in Java
•t1.start() <<<<< it is in Runnable state
•the start method moves the thread into the runnable
state. This does not mean that it will run immediately (there
may be another thread that is being run by the CPU)
•At certain times during the execution of a program that
contains threads, the Java system will have a look at all the
runnable threads and will select one to execute.
•Only the thread that is actually executing is said to be in
the running state. When a particular thread is chosen, its
run method is invoked and the thread can begin to execute
the code. It is now in the running state.
•t1.run() <<< is invoked by the scheduler and CPU
•When a running state finishes executing, it moves into the
finished state.
437
Creating Threads
• However, the thread may run out of its
allotted CPU time.

• Alternatively, it may invoke the yield


method to give way to other threads of
equal or higher priority.

• Both scenarios will cause the thread to go


back into the runnable state where it can,
at some point, be chosen by the Java run-
time system to move back into the
running state.

• Once it is back in the running state it can


carry on with the execution of its run
method at the point where it left off. This
is indicated by the resume label in the
figure.
438
Creating Threads
• From the running state, a thread may
move to the blocked state because of
• delays in I/O, or
• because the sleep method or
• wait method is invoked.
• The sleep method is a static method of
Thread.sleep(50)and so can be called in
any program, even those that do not use
the Thread class. When invoked, it puts the
thread to sleep for the specified
number of milliseconds.
• In the blocked state, the thread cannot
progress until something happens – for
example,
• an I/O transfer is completed
• Sleep is ended.
• notify(), notifyAll() <<<< Object
439
Creating Threads
• The wait, notify and notifyAll
methods:
– All three methods are inherited
from the Object class rather
than the Thread class
– The wait method causes a
thread to wait for notification by
another thread,
– The notify and notifyAll provide
such notification.

440
Creating Threads
• The important concept at this stage is that a Java program may involve a
number of threads, some of which are runnable and ready to be
executed by a processor and others that are unable to proceed because
they are blocked.
• On a single-processor machine only one thread can actually be running
at a time. The Java system has a component known as the scheduler
that makes decisions about which thread to run next.

• The decision as to when thread execution is switched will depend on the


underlying operating system:

– some operating systems switch when the currently running thread


becomes blocked,
– while others allocate set blocks of time to a thread.
441
Unit 8: Threads

442
Exercise
•(a) What are the two ways to define threads?
•(b) When a thread is executing, does it continue executing until it gets to
the end of its code?
•(c) How do you tell the system that you want to set a thread in running?

•ANSWERS .................................................................................................
...........
•(a) Threads can be defined by extending the Thread class or by
implementing the Runnable interface.
•(b) No, in all likelihood the thread will have access to the CPU for only a
short part of its execution before it is stopped and another thread is given
an opportunity to run.
•(c) After creating an instance of a threaded class, you invoke the start
method.
443
Exercise
•(a) When would you typically want to define a thread by implementing
Runnable rather than extending Thread?
•(b) How do you define, create and start a thread using Runnable?

•ANSWERS....................................................................................................
........
•(a) There are many occasions when a threaded class will inherit from
another class: for example, JFrame. As Java does not allow multiple
inheritance it is useful to be able to implement an interface to create a
thread. Remember, Java allows a class to implement any number of
interfaces but to extend only one other class.
•(b) The thread class is defined by implementing the interface Runnable
and the single method in the interface – run. You then create an instance
of this threaded class and pass this instance to the Thread constructor to
create a new threaded object. This can then be treated as any other
threaded object and can be started by invoking the start method. 444
Exercise
• (a) What is the difference between a thread in the blocked state and one
in the runnable state?
• (b) how do you explain the following
WhoamI t1 = new WhoamI("tota"); // initaile state
t1.start(); // <<<<< start state
t1.run(); <<<<<<<<<<<<<<<<<yes but out of the Thread mechanism
Who is responsible to invoke run() method
OS and scheduler
• ANSWERS.................................................................................................
...........
• (a) A runnable thread is fully ready to run once it is chosen by the
scheduler. On the other hand, a thread in the blocked state is definitely
not ready to run because
– it is waiting for something to happen.
– It may be waiting either for an I/O event to happen or because the wait
method has been invoked. 445

You might also like