You are on page 1of 242

CS111: PROGRAMMING

LANGUAGE II
Lecture 2 &3: Classes & objects
Lecture Contents
 What is a class?
 Class basics:
 Data
 Methods
 Objects
 Defining and using a class
 Access identifiers
 Private
 Public
 Set/get methods
 Data initialization
 What is a constructor?
 Defining constructors
 Overloading constructor
 Using this reference

Dr. Amal Khalifa, 2016


In Java
 Everything must be in a class. There are no
global functions or global data.

Dr. Amal Khalifa, 2016


Even Main??

Dr. Amal Khalifa, 2016


What is a class?
 Class:
 likea struct in C++, defines a data
type (blueprint)
 Combines data and operations in
one place:
 data / fields/ properties / state
variables
 Operations/ behavior / methods that
modify state

Dr. Amal Khalifa, 2016


What is a data type?
 Any data type includes
 Data (range of values)
 Operations (that can be performed on data)

 Example:
int data type has:
Data: +-32,767
Operations: +, - , * , / , %
 Same with classes
 Collection of data values together with set of basic
operations to be allowed for the values

Dr. Amal Khalifa, 2016


Encapsulation
• The bundling of data and procedures(methods) into a single unit(called class).
• Class : various data elements and member functions are wrapped up together.
• main feature of object oriented programming
Dr. Amal Khalifa, 2016
OOP
Objects & Classes
 Objects:
 represent ‘things’ from the
real world, or from some
problem domain (example:
“the red car down there in
the car park”)
 Class:
 representall objects of a
kind (example: “car”)

Dr. Amal Khalifa, 2016


Class = Blueprint
 One blueprint to create several similar, but different,
houses:

Dr. Amal Khalifa, 2016


How to define a Class??

Class
design

Object
creation

Member
access

Dr. Amal Khalifa, 2016


Defining Classes
12

 Identifying Class Attributes


 Classes have attributes (data) and operations (behaviors).
 Class attributes are implemented in Java programs as fields, and class
operations are implemented as methods.

Dr. Amal Khalifa, 2014


UML Class diagrams
 UML is a modeling language to capture the
architectural, behavioral and structural aspects of a
system.
 Class diagrams describes the objects in a system and
their relationships, so it is widely used by the developer
community.
 The UML representation of a class is a rectangle
containing three compartments stacked vertically.
 The top compartment shows the class's name.
 The middle compartment lists the class's attributes.
 The bottom compartment lists the class's operations.

Dr. Amal Khalifa, 2016


Examples
What about a student??

Dr. Amal Khalifa, 2016


The student class

Dr. Amal Khalifa, 2016


A class in Java

.java file- // Student.java


name extension public class Student {
The class // data..
keyword

Public
keyword 
access modifier //methods...
 class is
“available to //not static!!
the public

No main 
can’t execute
}

Dr. Amal Khalifa, 2016


Student Test

Another class. // StudentTest.java


Why not
public class Students {
Import public static void main (String[] args)
student.java?? {
Using new  //define object(s)
object
instantiation

Dot separator
//call a method

}
Dr. Amal Khalifa, 2016
Controlling Access to Members
 Access modifiers
 Public  Methods
 Client’s view of the services provided by the class
 Private  data
 not accessible outside the class (Data Hiding)
 protected.

Dr. Amal Khalifa, 2016


Private & public
• Public items (usually member functions) are "user-accessible“
• Outside of class definition, cannot change (or even access) private data

Dr. Amal Khalifa, 2016


Mark Visibility type
+ Public
# Protected
- Private
~ Package

Marks for UML-supported visibility types

Dr. Amal Khalifa, 2016


Example

. Modify class // Student.java


efinition public class Student {
// data  private

//methods  public

Dr. Amal Khalifa, 2016


Student Test

Try to access // StudentTest.java


private public class StudentTest {
members!!
public static void main (String[] args)
What about {
the public
ones ? //define object(s)

//access different members

}
Dr. Amal Khalifa, 2016
Set/get methods
• Object needs to “have access" to its data
• accessor methods
• Allow object to read data
• Also called "get methods"
• Simple retrieval of member data

• Mutator methods
• Allow object to change data
• Also called “set methods"
• Manipulated based on application
Dr. Amal Khalifa, 2016
Example: set/get methods
// Student.java
. Class
Methods have public class Student {
direct access // data
to class
members
(data or
methods) //methods

//set methods

//get methods

Dr. Amal Khalifa, 2016


Student Test

The set // StudentTest.java


method can public class StudentTest {
be used to
modify a data public static void main (String[] args)
field {
the get //define object(s)
method can
be used to
display the
updated
value //modify data!!

}
Dr. Amal Khalifa, 2016
Instance Variables, Initial values
 Primitive-type
 initialized by default
 byte,char, short, int, long, float and double initialized to 0
 Boolean initialized to false.

 non-primitive types (classes ) ,instance variable


 reference types : store the locations of objects in the
computer’s memory.
 not initialized by default.
 String ??

Dr. Amal Khalifa, 2016


Student Test

The set // StudentTest.java


method can public class StudentTest {
be used to
modify a data public static void main (String[] args)
field {
the get //define object(s)
method can
be used to
display the //print data without initialization!!
updated
value
}

Dr. Amal Khalifa, 2016


Initializing data with Constructors
 A constructor can be used to initialize an object of a
class when the object is created.

Dr. Amal Khalifa, 2016


Example: constructors
// Student.java
. Constructor
must be public public class Student {
// data
Same name
as class
//an empty constructor
no return type public Student()
Parameters?? {
}
//set/get methods

//other methods
}

Dr. Amal Khalifa, 2016


Student Test

Keyword new // StudentTest.java


calls the public class StudentTest {
class’s
constructor to public static void main (String[] args)
perform the {
initialization.
//define object(s)using empty
//constructor

//print data
}

Dr. Amal Khalifa, 2016


The default Constructor
 By default, the compiler provides a default
constructor with no parameters in any class that
does not explicitly include a constructor.
 If you declare any constructors for a class, the
Java compiler will not create a default constructor
for that class
 With the default constructor, its instance variables
are initialized to their default values.

Dr. Amal Khalifa, 2016


Overloaded Constructors
 Overloaded constructors
 enable objects of a class to be initialized in different
ways.
 multiple constructor declarations with different
signatures.
 the compiler differentiates signatures by :
 the number of parameters,
 the types of the parameters and
 the order of the parameter types in each signature.

Dr. Amal Khalifa, 2016


Example: constructors
// Student.java
Define more
Constructors public class Student {
// data
Parameters??

//constructors
public Student()
{
}
//set/get methods

//other methods
}

Dr. Amal Khalifa, 2016


Student Test

More objects // StudentTest.java


Different
public class StudentTest {
initialization public static void main (String[] args)
{
Same
methods, //define object(s)using different
different data //constructors

//print data
}

Dr. Amal Khalifa, 2016


Using this Reference
 Every object can access a reference to itself with
keyword this.
 Implicitly:
 referto the object’s instance variables and other methods
inside member methods.
 Enables the class’s code to know which object should be
manipulated.
 Explicitly:
 Can also use keyword this in a non-static method’s
body.

Dr. Amal Khalifa, 2016


Example :To learn the use "this" keyword

Dr. Amal Khalifa, 2016


Example reference
https://www.guru99.com/java-this-keyword.html

Dr. Amal Khalifa, 2016


Important hint

Dr. Amal Khalifa, 2016


Be careful!!

Dr. Amal Khalifa, 2016


That’s all for today…..
Text Book:
Chapter 3

Dr. Amal Khalifa, 2016


CS111: PROGRAMMING
LANGUAGE II
Computer Science
Department
Lecture 3 : Classes and Objects, A Deeper Look
Lecture Contents
2

 The Time class:


 data & methods
 Defining constructors
 Defining objects

 More on classes :
 The finalize method
 static members
 final members
 The student case study :
 static
 Arrays as data members

Dr. Amal Khalifa, 2014


Time2 Class Case Study
3

 Class Time2 represents the time of day in


universal-time format (24-hour clock format) .
 instance variables hour, minute and second
 methods:
 setTime
 toUniversalString ( hh:mm:ss)
 toString (hh:mm:ss AM/PM)
 5 overloaded constructors

Dr. Amal Khalifa, 2014


4 Dr. Amal Khalifa, 2014
5 Dr. Amal Khalifa, 2014
Time2 class
6

Use set
methods inside
constructors

Check for
valid inputs
Time2 class
7
Time2 class
8

Dr. Amal Khalifa, 2014


9 Dr. Amal Khalifa, 2014
10 Dr. Amal Khalifa, 2014
Default and No-Argument Constructors
11

 Every class must have at least one constructor.


 If you do not provide any constructors in a class’s declaration  the
compiler creates a default constructor
 If your class declares constructors, the compiler will not create a default
constructor.
 The default constructor :
 initializes the instance variables to their default values (zero for
primitive numeric types, false for boolean values and null for
references).

Dr. Amal Khalifa, 2014


Using this Reference
12

 Every object can access a reference to itself with


keyword this.
 Implicitly:
 referto the object’s instance variables and other methods
inside member methods.
 Enables the class’s code to know which object should be
manipulated.
 Explicitly:
 Can also use keyword this in a non-static method’s
body.

Dr. Amal Khalifa, 2014


Garbage Collection
13

 “resource leaks” are common in languages like C and C++


 The JVM performs automatic garbage collection:
 reclaim the memory occupied by objects that are no longer used.
 When there are no more references to an object, the object is
eligible to be collected.
 This typically occurs when the JVM executes its garbage collector.
 Done through the finalize of class Object (package
java.lang)

Dr. Amal Khalifa, 2014


Method finalize
14

 The finalize method :


 called by the garbage collector to perform termination
housekeeping on an object just before the garbage collector
reclaims the object’s memory.
 does not take parameters and has return type void.
 not guaranteed to execute at a specified time.
 It’s unclear if, or when, method finalize will be called.
 Programmers should avoid method finalize.

Dr. Amal Khalifa, 2014


static Class Members
15

 static field:
 called a class variable
 represents class-wide information—only one copy is
be shared by all objects of a class.
 The declaration begins with the keyword static.
 public static members can be accessed through a
reference to any object of the class, or by qualifying the
member name with the class name and a dot (.).
 If a static variable is not initialized, the compiler assigns
it a default value.

Dr. Amal Khalifa, 2014


static Class Members (Cont.)
16

 To access a static member when no objects of the


class exist :
 Public: prefix the class name and a dot (.) to the
static member, as in Math.PI.
 private : provide a public static method and
call it by qualifying its name with the class name and
a dot.

Dr. Amal Khalifa, 2014


Example
17

A static
variable is
accessible by
all methods in
a class
Example
18

Static methods
are used to
access static
variables

Static methods
can be called
whether or not
there are any
objects or not

Dr. Amal Khalifa, 2014


Example
19

Call to static
method either
through the
class name or
created
objects
Example
20

Good practice
to set
references to
null for
garbage
collector
static Class Members (Cont.)
21

 A static method cannot access non-static


class members
 the this reference cannot be used in a static
method.
 The this reference must refer to a specific object of the
class, and when a static method is called, there might not
be any objects of its class in memory.

Dr. Amal Khalifa, 2014


static Import
22

 A static import:
 enables you to access the static members of a class
via their unqualified names (class name and a dot (.)
are not required)
 Two forms
 One that imports a particular static member (which
is known as single static import)
 One that imports all static members of a class
(which is known as static import on demand)

Dr. Amal Khalifa, 2014


Example
23

Use Math
functions with
their simple
names
final Instance Variables
24

 Keyword final :
 specifies that a variable is not modifiable (i.e., it’s a constant)
private final int INCREMENT;
 Preventing code from accidental modification of
variable values.
 final variables can be initialized:
 when they are declared, or
 by each of the class’s constructors so that each object
of the class has a different value.
 If a class provides multiple constructors, every one would be
required to initialize each final variable.
Dr. Amal Khalifa, 2014
Example
25

Final
variables must
be initialized
in constructor
Example
26

Use
constructor
to initialize
final
member
27 Dr. Amal Khalifa, 2014
Apply on Student class!!
28

 static members:
 Add a static field to count the number of active student
objects.
 Add the needed methods to access the count
information
 Enrolled courses
 Max / semester = 7
 Arrays?

Dr. Amal Khalifa, 2014


29 That’s all …
Text Book:
Chapter 8

Dr. Amal Khalifa, 2014


CS111: PROGRAMMING
LANGUAGE II
Computer Science
Department
Lecture 4 : Composition
Lecture Contents
2

 Composition
 What?

 When?

 How?

 Case Study

Dr. Amal Khalifa, 2016


Composition
3

 A class can have references to objects of other classes


as members.
 This is called composition and is sometimes referred to
as a has-a relationship.
 Examples:
 An AlarmClock object needs two references to Time
objects to know the current time and the time when it’s
supposed to sound its alarm.
 A Robot Object has-a MechanicalArm
 A car Object has-a Wheel
 A student Object has-a BirthDate
 You name it !!!

Dr. Amal Khalifa, 2016


Example
4

Date class

Full constructor

Check input
values

Dr. Amal Khalifa, 2016


Example
5

Check input
ranges

Dr. Amal Khalifa, 2016


Example
6

Leap year??

Output format

Dr. Amal Khalifa, 2016


Example
7

Reference to
objects of
other classes

Dr. Amal Khalifa, 2016


Test
8

Date objects
used to
initialize date
objects

Implicit call to
the toString()
method

Dr. Amal Khalifa, 2016


More examples!!
9

 Modify The Student class to contain two Date


Objects:
 dateOfBirth

 admissionDate

 Add a new constructor to initialize the new data


members
 Define an object and specify the birth date as
12/3/1990 and admission on 21/8/2013

Dr. Amal Khalifa, 2016


10 That’s all …
Text Book:
Chapter 8

Dr. Amal Khalifa, 2016


CS111: PROGRAMMING
LANGUAGE II
Computer Science
Department
Lecture 4&5: Inheritance
Lecture Contents
2

 What is Inheritance?
 Super-class & sub class
 The object class
 Using extends keyword
 @override keyword
 Creating subclasses
 Protected members
 What is protected?
 Data Hiding issues
 Inheritance Hierarchy
 Case study : Campus Community
 Constructors call chain

Dr. Amal Khalifa, 2016


OOP

3 Dr. Amal Khalifa, 2016


OOP - Inheritance
4

 A class can extend another class, inheriting all its data


members and methods while redefining some of them
and/or adding its own.

Dr. Amal Khalifa, 2016


OOP - Inheritance
5

 Inheritance represents the is a relationship between


data types (e.g. student/person)
 Existing class is the superclass (more general)
 New class is the subclass (more specific)
 Java supports only single inheritance
 each class is derived from exactly one direct
superclass.
 Possible to Create hierarchy of classes

Dr. Amal Khalifa, 2016


Superclasses and Subclasses
6

Superclasses
“more
general”

subclasses
 “more
specific.”

every
subclass
object is an
object of its
superclass

Dr. Amal Khalifa, 2016


The Object Class
7

 The Java class hierarchy begins with class Object


(in package java.lang)
 Every class in Java directly or indirectly extends (or
“inherits from”) Object.
 All classes in Java inherit directly or indirectly from
Object, so its 11 methods are inherited by all other
classes.

Dr. Amal Khalifa, 2016


The Object Class
8

Dr. Amal Khalifa, 2016


The Object Class
9

Dr. Amal Khalifa, 2016


The Object Class
10

learn more about Object’s methods at:


java.sun.com/javase-6/docs/api/java/lang/Object.html
Or
java.sun.com/docs/books/tutorial/java/IandI/
objectclass.html Dr. Amal Khalifa, 2016
Apply on Student class
11

 Does your class extends Object?


 If you don’t explicitly specify which class a new class extends, the
class extends Object implicitly.
 What methods did you redefine (override)?
 finalize()
 toString()
 equals()

 To override a superclass method, a subclass must


declare a method with the same signature as the
superclass method  or a compilation error occurs
 @Override annotation

Dr. Amal Khalifa, 2016


12 Programming Pitfalls!!

Dr. Amal Khalifa, 2016


Example: CommissionEmployee Class
13

 Inheritance hierarchy containing types of


employees in a company’s payroll application
 Commission employees are paid a percentage of their
sales

Dr. Amal Khalifa, 2016


Class CommissionEmployee
14

Extends
object not
required; this
will be done
implicitly

Constructors
are not
inherited

Dr. Amal Khalifa, 2016


Class CommissionEmployee
15

Set/get
methods

Dr. Amal Khalifa, 2016


Class CommissionEmployee
16

Set/get
methods

Dr. Amal Khalifa, 2016


Class CommissionEmployee
17

Set/get
methods

Dr. Amal Khalifa, 2016


Class CommissionEmployee
18

@Override
ensures
overridded
method has
the same
signature as
the base class

Dr. Amal Khalifa, 2016


Test
19

New
employee
object

Dr. Amal Khalifa, 2016


Test
20

Implicit call
to the
method
toString

Dr. Amal Khalifa, 2016


Creating a new class!!
21

 Base-salaried commission employees receive a base


salary plus a percentage of their sales.
 Class BasePlusCommissionEmployee:
 Data: first name, last name, social security number, gross
sales amount, commission rate and base salary.
(( All but the base salary are in common with class
CommissionEmployee)).
 services: a constructor, and methods earnings,
toString and get and set for each instance variable
((Most are in common with class CommissionEmployee ))

Dr. Amal Khalifa, 2016


Creating a new class
22

Copy & paste Inheritance


 copy  Extend an existing class and
CommissionEmployee add only the needed
code, pasted it into
BasePlusCommissionEm data/functionality
ployee  Reusability  Don’t reinvent
 modify the new class to the wheel!!
include a base salary and
methods that manipulate the
base salary.
 error prone
 time consuming.
 Too many copies of the
same code  bad
maintenance Dr. Amal Khalifa, 2016
Superclasses and Subclasses
23

 Inheritance issue
 A subclass can inherit methods that it does not need or
should not have.
 Even when a superclass method is appropriate for a
subclass, that subclass often needs a customized
version of the method.
 The subclass can override (redefine) the superclass
method with an appropriate implementation.
 An overrided subclass method can access the superclass method
using the keyword super and a dot (.) separator.

Dr. Amal Khalifa, 2016


BasePlusCommissionEmployee Class
24

New class
defined
based on an
existing one

The first task


of a subclass
constructor is
to call its
direct
superclass’s
constructor
explicitly or
implicitly to
handle
initialization

Dr. Amal Khalifa, 2016


BasePlus-CommissionEmployee Class
25

public
members are
accessible
from
anywhere

private
members are
accessible
only within the
class itself.

Dr. Amal Khalifa, 2016


Errors!!
26

A superclass’s
private
members are
hidden in its
subclasses

Compilation
errors occur
when the
subclass
attempts to
access the
superclass’s
private
instance
variables.

Dr. Amal Khalifa, 2016


27 Programming Pitfalls
To enable a subclass to directly access superclass instance variables,
we can declare those members as protected in the superclass
Dr. Amal Khalifa, 2016
Protected Members
28

 To enable a subclass to directly access superclass instance


variables, we can declare those members as protected in
the superclass.
 an intermediate level of access between public and private.
 can be accessed by members of that superclass, by members of its
subclasses and by members of other classes in the same package
(package access).
 All public and protected superclass members retain their
original access modifier when they become members of the subclass.

Dr. Amal Khalifa, 2016


Notes on Using protected Instance Variables
29

 Using protected instance variables creates


several potential problems.
 A subclass object can assign an invalid value to the
variable, possibly leaving the object in an inconsistent
state.
 Subclasses should depend only on the superclass
services and not on the superclass data
implementation.
 A class’s protected members are visible to all
classes in the same package as the class containing the
protected members—this is not always desirable.

Dr. Amal Khalifa, 2016


30 Programming Pitfalls!!

Dr. Amal Khalifa, 2016


Data Hiding
31

What if data
is private??

Encapsulation
 better
design

Dr. Amal Khalifa, 2016


32 Dr. Amal Khalifa, 2016
33 Dr. Amal Khalifa, 2016
34 Dr. Amal Khalifa, 2016
35 Dr. Amal Khalifa, 2016
New class
36

Use set/get,
either within
class or in
subclasses

Information
hiding

Dr. Amal Khalifa, 2016


37 Dr. Amal Khalifa, 2016
Inheritance Hierarchy
38

 A superclass exists in a hierarchical relationship with its


subclasses.
 Each arrow in the Inheritance hierarchy represents an is-a
relationship.
 The direct superclass is the superclass from which the
subclass explicitly inherits.
 An indirect superclass is any class above the direct superclass
in the class hierarchy.

Dr. Amal Khalifa, 2016


Inheritance Hierarchy
39

Starting from
the bottom,
you can follow
the arrows
and apply the
is-a
relationship
up to the
topmost
superclass.

A Triangle is a TwoDimensionalShape and is a Shape

A Sphere is a ThreeDimensionalShape and is a Shape.

Dr. Amal Khalifa, 2016


Constructors call chain
40

 Instantiating a subclass object begins a chain of constructor


calls
 The subclass constructor, before performing its own tasks, invokes
its direct superclass’s constructor
 If the superclass is derived from another class, the superclass
constructor invokes the constructor of the next class up the
hierarchy, and so on.
 The last constructor called in the chain is always class Object’s
constructor.
 Original subclass constructor’s body finishes executing last.

Dr. Amal Khalifa, 2016


Constructors in Subclasses
41

 Constructors are not inherited.


 The first task of a subclass constructor is to call its
direct superclass’s constructor explicitly or implicitly
 Ensures that the instance variables inherited from the
superclass are initialized properly.
 If the code does not include an explicit call to the
superclass constructor, Java implicitly calls the
superclass’s default or no-argument constructor.
 A class’s default constructor calls the superclass’s
default or no-argument constructor.
Dr. Amal Khalifa, 2016
Case Study: Campus Community
42

CommunityMember is the direct superclass of Employee, Student


and Alumnus and is an indirect superclass of all the other classes
in the diagram. Dr. Amal Khalifa, 2016
Class Design
43

CommunityMember

 First Name
 Last Name
 SSN
 BirthDate

Dr. Amal Khalifa, 2016


Class Design
44

Employee Student

 Title  UnvID
 HireDate  Faculty
 Salary  Level

Dr. Amal Khalifa, 2016


Class Design
45

Faculty Staff

 Degree(BSc, MSc, PhD)  Full/partTime


 Specialty

Dr. Amal Khalifa, 2016


46 That’s all,,,
Text Book ref.
Chapter 9

Dr. Amal Khalifa, 2016


1

CS111: PROGRAMMING
LANGUAGE II
Computer Science
Department
Lecture 6: Arrays & ArrayLists
Lecture Contents
2

 What is a Array?
 Arrays of objects
 ArrayList

Dr. Amal Khalifa, 2014


Arrays
3

 What is an array?
 data structures
 related data items of the same type.
 fixed length once created.
 Elements referred to using index or subscript.

 In java, Arrays are objects, so they’re considered reference


types.
 Every array object knows its own length and stores it in a
length instance variable.
 Elements can be either primitive types or reference types.
4
Arrays of objects
5

declare
MyClass[] arr;

create
arr = new MyClass[SIZE];

initialize
for(int i=0;i<SIZE;i++)
arr[i] = new MyClass(…);
The Student Class
6

public class Student extends CommunityMember{


private String UnvId;
private String Faculty;
private int Level;
public Student(String FName, String LName, String ssn,
MyDate dob, String id, String faculty, int level)
{
super( FName, LName, ssn, dob);
setFaculty(faculty);
setUnvId(id);
setLevel(level);
}
public void setUnvId(String UnvId) {
this.UnvId = UnvId;
}
Computer Science Department
The Student Class
7

public void setFaculty(String Faculty) {


this.Faculty = Faculty;
}
public void setLevel(int Level) {
this.Level = Level;
}
public String getUnvId() {
return UnvId;
}
public String getFaculty() {
return Faculty;
}
public int getLevel() {
return Level;
}

Computer Science Department


The Student Class
8

@Override
public String toString() {
return "Student{" + super.toString() + "\nUnvId = " +
UnvId + ", Faculty= " + Faculty + ", Level= " + Level + '}';
}

Computer Science Department


Case Study
9

 Create an array of Students with the following data:


Name SSN DoB UnvId Faculty Level
Malak Hamad 12345 12-3-1997 22222 Arts 2
Maryam Nabil 34567 10-2-1998 33333 Medicine 1
Salma Hamdy 47689 3-5-1995 44444 Computer 3
Science
 Then do the following:
 Set the level of first student to 4
 Modify the date of birth of “Maryam Nabil” to 12-22-
1999
 Change the faculty of the last student object to “Dentistry”

Computer Science Department


10

Student[] arr = new Student[3];


Student s = new Student("Malak", "Hamad", "12345",new
MyDate(12,3,1997),"22222", "Arts", 2);
arr[0] = s;
arr[1] = new Student("Maryam", "Nabil", "34567",new
MyDate(10,2,1998),"33333", "Medicine", 1);
arr[2] = new Student("Salma", "Hamdy", "47689",new
MyDate(3,5,1995),"44444", "Computer Science",
3);
arr[2].setFaculty("Design");
for (Student elm : arr)
System.out.println(elm);
Computer Science Department
Collections and Class ArrayList
11

 Collections provide efficient methods that organize,


store and retrieve your data without requiring
knowledge of how the data is being stored.
 The collection class ArrayList<T> :
 from package java.util
 can dynamically change its size to accommodate more
elements.
 generic classes : can be used with any type.

Dr. Amal Khalifa, 2014


ArrayList
12

 ArrayList<T> List = new ArrayList<T>();


 The T is a placeholder:
 when declaring a new ArrayList, replace it with the type of
elements that you want the ArrayList to hold.
 only non-primitive types can be used with these collection classes.
 Example:
ArrayList<Student> List = new
ArrayList<Student>();

Computer Science Department


13 Properties of ArrayList

Dr. Amal Khalifa, 2014


Case Study: revisited
14

 Create an ArrayList of the following Students data :


Name SSN DoB UnvId Faculty Level
Malak Hamad 12345 12-3-1997 22222 Arts 2
Maryam Nabil 34567 10-2-1998 33333 Medicine 1
Salma Hamdy 47689 3-5-1995 44444 Computer 3
Science

 Then do the following:


 Setthe date of birth of the first student to 22-2-1998
 Modify the level of the last student object to 5
 Change the faculty of “Maryam Nabil” to “Dentistry”

Computer Science Department


15

//don’t forget
//import java.util.ArrayList
ArrayList<Student> MyList = new ArrayList<Student>();
System.out.println("before add " + MyList.size());
MyList.add(new Student("Malak", "Hamad", "12345",new
MyDate(12,3,1997),"22222", "Arts", 2));

MyList.add(new Student("Maryam", "Nabil", "34567",new


MyDate(10,2,1998),"33333", "Medicine", 1));
MyList.add(new Student("Salma", "Hamdy", "47689",new
MyDate(3,5,1995),"44444", "Computer Science", 3));
Computer Science Department
16 That’s all…
Text Book ref.:
Chapter 7 (7.14)

Computer Science Department


CS111: PROGRAMMING
LANGUAGE II
Computer Science
Department
Lecture 7: Polymorphism
Lecture Contents
2

 What is polymorphism?
 Demonstratingpolymorphic behavior.
 Overridden methods and polymorphism

 Abstract base classes


 Concrete classes
 Case Study

 Polymorphic processing

 final classes and methods

dr. Amal Khalifa, 2016


OOP

3 dr. Amal Khalifa, 2016


What is Polymorphism?
4

 Polymorphism enables you to write programs that


process objects that share the same superclass can be
manipulated in the same way
 simplify programming.

dr. Amal Khalifa, 2016


What is Polymorphism?
5

 Polymorphism literally means many forms


 Essentially we are able to get many different
types of object behavior from a single
reference type
 This enables us to write easily extensible
applications

dr. Amal Khalifa, 2016


What is Polymorphism?
6

For example in a computer game that simulates the


movement of animals we can send ‘move’ commands to
different types of animal
 We send the commands via an animal reference which is

the base class for the different animal types


 But each type behaves differently once it receives the
command
 Such an approach leads to a readily extendable
application

dr. Amal Khalifa, 2016


What is Polymorphism?
7

Application

animal Move

dr. Amal Khalifa, 2016


Introduction
8

 a superclass reference at a subclass object. (crossover)


 Allowed because each subclass object is an object of
its superclass.
 The type of the referenced object, not the type of the
variable, determines which method is called.
 Invoking a method on a subclass object via a
superclass reference invokes the subclass
functionality

dr. Amal Khalifa, 2016


Case Study
9

 In the next example:


 Practice cross over!!
 an object of a subclass can be treated as an object of its
superclass, enabling various interesting manipulations.

dr. Amal Khalifa, 2016


Example
10

Each object uses


his own
constructor to
do the required
initialization

dr. Amal Khalifa, 2016


11 dr. Amal Khalifa, 2016
12 dr. Amal Khalifa, 2016
Polymorphic Behavior
13

 When the compiler encounters a method call made through


a variable, the compiler determines if the method can be
called by checking the variable’s class type.
 If that class contains the proper method declaration (or inherits one),
the call is compiled.
 At execution time, the type of the object to which the
variable refers determines the actual method to use.
 This process is called dynamic binding.

dr. Amal Khalifa, 2016


Case Study
14

 create an ArrayList<T> of superclass variables


 Each element of the array refers to objects of many subclass types.
 Again, polymorphic behavior!!

dr. Amal Khalifa, 2016


Abstract Classes and Methods
15

CommunityMember is not supposed to be used to create objects


 abstract superclass
dr. Amal Khalifa, 2016
Abstract Classes and Methods
16

 Abstract classes
 Sometimes it’s useful to declare classes for which you never intend to
create objects.
 Cannot be used to instantiate objects—abstract classes are incomplete.
 An abstract class provides a superclass from which other classes can
inherit and thus share a common design.
 Used only as superclasses in inheritance hierarchies, so they are
sometimes called abstract superclasses.
 Not all hierarchies contain abstract classes.
 Abstract classes sometimes constitute several levels of a hierarchy.

dr. Amal Khalifa, 2016


Abstract Classes and Methods
17

 Declared with the keyword abstract.


 normally contains one or more abstract methods.
 Declared with keyword abstract
public abstract void draw(); // abstract method
 do not provide implementations.
 A class that contains abstract methods must be an abstract class
even if that class contains some concrete (nonabstract) methods.
 Constructors and static methods cannot be declared
abstract.

dr. Amal Khalifa, 2016


Concrete Classes
18

 Classes that can be used to instantiate objects are


called concrete classes.
 must declare the “missing pieces” in their abstract
superclasses
 provide implementations of every method they declare
(some of the implementations can be inherited).
 make it reasonable to instantiate objects.

dr. Amal Khalifa, 2016


19 Programming Pitfalls!!
Working with abstract base classes

dr. Amal Khalifa, 2016


Case Study: Payroll System
20

A company pays its employees on a weekly basis.


The employees are of four types: Salaried
employees are paid a fixed weekly salary
regardless of the number of hours worked,
hourly employees are paid by the hour and
receive overtime pay (i.e., 1.5 times their
hourly salary rate) for all hours worked in
excess of 40 hours, commission employees are
paid a percentage of their sales and base-
salaried commission employees receive a base
salary plus a percentage of their sales. For
the current pay period, the company has
decided to reward salaried-commission
employees by adding 10% to their base
salaries. The company wants to write a Java
application that performs its payroll
calculations polymorphically.
dr. Amal Khalifa, 2016
21
Abstract class names are italicized in the UML.

dr. Amal Khalifa, 2016


Abstract Superclass Employee
22

 Each Employee has:


 first name,
 last name, and
 a social security number
 Class Employee provides :
 toString method
 the get and set methods for instance variables.
 An earnings method
 An abstract method—there is not enough information to
determine what amount earnings should return.
 applies to all employees,
 each earnings calculation depends on the employee’s class.
 Each subclass overrides earnings with an appropriate implementation.
dr. Amal Khalifa, 2016
Concrete Subclasses
23

dr. Amal Khalifa, 2016


The Employee class
24

Abstract class

abstract
keyword

dr. Amal Khalifa, 2016


25 dr. Amal Khalifa, 2016
26 dr. Amal Khalifa, 2016
SalariedEmployee class
27

One concrete
class

dr. Amal Khalifa, 2016


28 dr. Amal Khalifa, 2016
HourlyEmployee class
29

hourly
employees
are paid by
the hour and
receive
overtime pay
(i.e., 1.5 times
their hourly
salary rate)
for all hours
worked in
excess of 40
hours,

dr. Amal Khalifa, 2016


30 dr. Amal Khalifa, 2016
31 dr. Amal Khalifa, 2016
CommissionEmployee class
32

commission
employees
are paid a
percentage
of their
sales

dr. Amal Khalifa, 2016


33 dr. Amal Khalifa, 2016
BasePlusCommissionEmployee
34
class
The last one!!

dr. Amal Khalifa, 2016


35 dr. Amal Khalifa, 2016
Polymorphic Processing
36

Array of
references to
the base class

Each reference
is instantiated
as an object of
a concrete
class.

Dynamic
binding 
different
method calls
according to
actual type!!

dr. Amal Khalifa, 2016


37 dr. Amal Khalifa, 2016
38

downcasting
enables a
program to
invoke
subclass
methods that
are not in the
superclass.

getClass
method
returns an
object of type
Class including
its class name.
39 dr. Amal Khalifa, 2016
40 dr. Amal Khalifa, 2016
41 dr. Amal Khalifa, 2016
Polymorphism Example
42

 Suppose we create a program that simulates the


movement of several types of animals for a biological
study. Classes Fish, Frog and Bird represent the three
types of animals under investigation.
 Each class extends superclass Animal, which contains a
method move and maintains an animal’s current location as x-
y coordinates. Each subclass implements method move.
 A program maintains an Animal array containing references
to objects of the various Animal subclasses. To simulate the
animals’ movements, the program sends each object the same
message once per second—namely, move.
dr. Amal Khalifa, 2016
Benefits of Polymorphism
43

 With polymorphism, we can design and


implement systems that are easily extensible
 New classes can be added with little or no
modification to the general portions of the program, as
long as the new classes are part of the inheritance
hierarchy that the program processes generically.
 The only parts of a program that must be altered to
accommodate new classes are those that require direct
knowledge of the new classes that we add to the
hierarchy.
dr. Amal Khalifa, 2016
final Methods
44

 A final method in a superclass cannot be overridden


in a subclass.
 Methods that are declared private are implicitly final,
because it’s not possible to override them in a subclass.
 Methods that are declared static are implicitly final.
 A final method’s declaration can never change, so all
subclasses use the same method implementation, and calls
to final methods are resolved at compile time—this is
known as static binding.

dr. Amal Khalifa, 2016


final Classes
45

 A final class cannot be a superclass (i.e., a class


cannot extend a final class).
 All methods in a final class are implicitly final.
 Example : Class String is an example of a final
class.
 programs that use Strings can rely on the functionality
of String objects as specified in the Java API.

dr. Amal Khalifa, 2016


46 Programming Pitfalls

dr. Amal Khalifa, 2016


47 That’s all…
Text Book ref.:
Chapter 10
Chapter 7 (7.14)

dr. Amal Khalifa, 2016


CS111: PROGRAMMING
LANGUAGE II
Computer Science
Department
Lecture 8: Interfaces
Lecture Contents
2

 What is an interface?
 Creating and using interfaces in java

dr. Amal Khalifa, 2016


Introduction to Interfaces
3

 Interfaces define and standardize the ways in


which things such as people and systems can
interact with one another.
 Example: The controls on a radio serve as an interface
between radio users and a radio’s internal components.
 Can perform only a limited set of operations (e.g.,
change the station, adjust the volume, choose between
AM and FM)
 Different radios may implement the controls in
different ways (e.g., using push buttons, dials, voice
dr. Amal Khalifa, 2016
commands).
Introduction to Interfaces
4

 The interface specifies what operations a radio


must permit users to perform but does not
specify how the operations are performed.
 A Java interface describes a set of methods
that can be called on an object.
 Interfaces offer a capability requiring that

unrelated classes implement a set of common


methods.

dr. Amal Khalifa, 2016


Introduction to Interfaces
5

 An interface describes a set of methods that


can be called on an object, but does not
provide concrete implementations for all the
methods.
 Sometime called “Pure Abstract Base Classes”.
 You can declare classes that implement (i.e.,
provide concrete implementations for the methods
of) one or more interfaces.
 Each interface method must be declared in all the
classes that explicitly implement the interface.
dr. Amal Khalifa, 2016
Introduction to Interfaces
6

 An interface is often used when disparate (i.e.,


unrelated) classes need to share common
methods and constants.
 Allows objects of unrelated classes to be processed
polymorphically by responding to the same method
calls.
 You can create an interface that describes the
desired functionality, then implement this interface
in any classes that require that functionality.

dr. Amal Khalifa, 2016


Syntax: Creating Interfaces
7

 An interface declaration begins with the keyword


interface and contains only constants and
abstract methods.
 All interface members must be public.
 Interfaces may not specify any implementation details,
such as concrete method declarations and instance
variables.
 All methods declared in an interface are implicitly
public abstract methods.
 All fields are implicitly public, static and final.
dr. Amal Khalifa, 2016
Syntax: Using Interfaces
8

 To use an interface, a concrete class must specify that


it implements the interface and must declare each
method in the interface with specified signature.
 Add the implements keyword and the name of the
interface to the end of your class declaration’s first line.
 Implementing an interface is like signing a contract
with the compiler that states:
“I will declare all the methods specified by the
interface or I will declare my class abstract.”

dr. Amal Khalifa, 2016


Syntax
9

 To implement more than one interface, use a


comma-separated list of interface names after
keyword implements in the class
declaration, as in:
public class ClassName extends
SuperclassName
implements FirstInterface,
SecondInterface, …

dr. Amal Khalifa, 2016


Case Study: Payroll System
10

 Suppose that the company involved wishes to perform


several accounting operations in a single accounts
payable application
 Required operations have to do with obtaining some kind
of payment amount.
 For an employee, the payment refers to the employee’s
earnings.
 For an invoice, the payment refers to the total cost of the goods
listed on the invoice.
 The application should determine payments for
employees and invoices alike.
dr. Amal Khalifa, 2016
Note:
oThe UML distinguishes an interface from other
classes by placing «interface» above the interface
name.
oThe UML expresses the relationship between a class
and an interface through a realization (modeled as a
11
dashed arrow with a a hollow arrowhead) dr. Amal Khalifa, 2016
12 dr. Amal Khalifa, 2016
13 dr. Amal Khalifa, 2016
14 dr. Amal Khalifa, 2016
15 dr. Amal Khalifa, 2016
16 dr. Amal Khalifa, 2016
Employee hierarchy Implements Payable
17

When a class
implements an
interface, it
should
implement
each of the
methods in the
interface or
declared
abstract.

dr. Amal Khalifa, 2016


18 dr. Amal Khalifa, 2016
19 dr. Amal Khalifa, 2016
20

Any concrete
subclass of the
abstract class
inherits the
superclass’s
contract and
thus must
implement the
interface
methods.

dr. Amal Khalifa, 2016


21 dr. Amal Khalifa, 2016
Polymorphic Processing
22

dr. Amal Khalifa, 2016


Polymorphic Processing
23

Objects of
any subclasses
of a class that
implements an
interface can
also be
thought of as
objects of the
interface
type.

dr. Amal Khalifa, 2016


24 dr. Amal Khalifa, 2016
Benefits of Interfaces
25

 Once a class implements an interface, all objects of that


class have an is-a relationship with the interface type, and
all objects of the class are guaranteed to provide the
functionality described by the interface.
 This is true of all subclasses of that class as well.
 Interfaces are particularly useful for assigning common
functionality to possibly unrelated classes.
 Allows objects of unrelated classes to be processed
polymorphically—objects of classes that implement the same
interface can respond to all of the interface method calls.
dr. Amal Khalifa, 2016
Common Interfaces of the Java API
26

 The Java API’s interfaces enable you to use your


own classes within the frameworks provided by
Java, such as comparing objects of your own types
and creating tasks that can execute concurrently
with other tasks in the same program.

dr. Amal Khalifa, 2016


27 dr. Amal Khalifa, 2016
28 dr. Amal Khalifa, 2016
29 That’s all for today…..
Chapter 10…..

dr. Amal Khalifa, 2016


CS111: PROGRAMMING
LANGUAGE II
Computer Science
Department
Lecture 11 : Exception Handling
Lecture Contents
2

 What is a Exception handling?


 basics:
 try

 catch

 Finally
 throws clause
 Types of exceptions

Dr. Amal Khalifa, 2016


Exception Handling
3

 Exception—an indication of a problem that occurs


during a program’s execution.
 With exception handling, a program can continue
executing (rather than terminating) after dealing
with a problem.
 Mission-criticalor business-critical computing.
 Robust and fault-tolerant programs (i.e., programs that
can deal with problems as they arise and continue
executing).

Dr. Amal Khalifa, 2016


Exception Handling
4

 Examples:
 ArrayIndexOutOfBoundsException occurs
when an attempt is made to access an element past
either end of an array.
 ClassCastException occurs when an attempt is
made to cast an object that does not have an is-a
relationship with the type specified in the cast operator.
 NullPointerException occurs when a null
reference is used where an object is expected.

Dr. Amal Khalifa, 2016


Exception Handling
5

 Only classes that extend Throwable (package


java.lang) directly or indirectly can be used
with exception handling.
 Exceptions are thrown (i.e., the exception occurs)
when a method detects a problem and is unable to
handle it.
 Stack trace—information displayed when an
exception occurs and is not handled.

Dr. Amal Khalifa, 2016


Exception Handling
6

 Information includes:
 The name of the exception in a descriptive message
that indicates the problem that occurred
 The method-call stack (i.e., the call chain) at the time it
occurred. Represents the path of execution that led to
the exception method by method.
 This information helps you debug the program.

Dr. Amal Khalifa, 2016


Example: Divide by Zero_ver1
7

 Java does not allow division by zero in integer arithmetic.


 Throws an ArithmeticException.
 Can arise from a several problems, so an error message (e.g.,
“/ by zero”) provides more specific information.
 Java does allow division by zero with floating-point values.
 Such a calculation results in the value positive or negative infinity
 Floating-point value that displays as Infinity or -Infinity.
 If 0.0 is divided by 0.0, the result is NaN (not a number), which is
represented as a floating-point value that displays as NaN.

Dr. Amal Khalifa, 2016


8 Dr. Amal Khalifa, 2016
9 Dr. Amal Khalifa, 2016
Output
10

Last “at” line in


the stack trace
started the call
chain.

Each line contains


the class name
and method
followed by the
file name and
line number.

The top “at” line


of the call chain
indicates the
throw point—the
initial point at
which the
exception occurs.

Dr. Amal Khalifa, 2016


Notes
11

 When a method throws an exception, the method


terminates and does not return a value, and its local
variables go out of scope.
 Ifthe local variables were references to objects and
there were no other references to those objects, the
objects would be available for garbage collection.

Dr. Amal Khalifa, 2016


Example: Divide by Zero_ver2
12

 Prior examples that read numeric values from the user


assumed that the user would input a proper integer value.
 Users sometimes make mistakes and input noninteger
values.
 An InputMismatchException occurs when
Scanner method nextInt receives a String that does
not represent a valid integer.
 If a stack trace contains “Unknown Source” for a
particular method, the debugging symbols for that method’s
class were not available to the JVM—this is typically the
case for the classes of the Java API.

Dr. Amal Khalifa, 2016


Example: Divide by Zero_ver2
13

throws
clause—
specifies the
exceptions a
method
throws.

can throw
exceptions of
the classes
listed in its
throws clause
or of their
subclasses.

Dr. Amal Khalifa, 2016


14

try block
encloses code
that might throw
an exception

ArithmeticExcepti
ons and
InputMistmatchEx
ceptions may
arise.

If the user makes


a mistake, the
program catches
and handles
allowing the user
to try to enter
the input again.

Dr. Amal Khalifa, 2016


15

When an
exception
occurs in a try
block, the
catch block
that executes
is the first one
whose type
matches the
type of the
exception that
occurred
Use the
System.err
object to
output error
messages.

Dr. Amal Khalifa, 2016


16 Dr. Amal Khalifa, 2016
17 Exception Handling mechanism
• The statements in the finally clause are executed after :
• the statements in the try block complete  no exceptions
• the statements in the appropriate catch clause complete  an exception is
generated
Try_catch Mechanism
18

 If an exception occurs in a try block:


 the try block terminates immediately
 program control transfers to the first matching catch block.
 If there multiple catch blocks match a particular exception type, only the
first matching catch block executes.
 Any remaining catch blocks in the try statement are ignored
 execution resumes at the first line of code after the try…catch
sequence.
 A finally block, if one is present, is executed.
 If no exceptions are thrown in a try block:
 the catch blocks are skipped
 control continues with the first statement after the catch blocks
 A finally block, if one is present, is executed.
Dr. Amal Khalifa, 2016
19 Be careful!!
Uncaught exception—one for which there are no matching catch blocks.

Dr. Amal Khalifa, 2016


When to Use Exception Handling
20

 Exception handling is designed to process


synchronous errors, which occur when a statement
executes.
 Common examples in this book:
 out-of-range array indices
 arithmetic overflow
 division by zero
 invalid method parameters
 unsuccessful memory allocation
 disk I/O completions

Dr. Amal Khalifa, 2016


Java Exception Hierarchy
21

 Exception classes inherit directly or indirectly from


class Exception, forming an inheritance
hierarchy.
 Can extend this hierarchy with your own exception
classes.

Dr. Amal Khalifa, 2016


22 Java Exception Hierarchy
• class Throwable (a subclass of Object) is the superclass of class
Exception.
• Only Throwable objects can be used with the exception-handling mechanism.

• Class Throwable has two Dr. Exception


Amal Khalifa,
subclasses: 2016 and Error
Java Exception Hierarchy
23

 Checked exceptions vs. unchecked exceptions.


 Compiler enforces a catch-or-declare requirement for checked
exceptions.
 The compiler checks each method call and method
declaration to determine whether the method throws
checked exceptions.
 If so, the compiler verifies that the checked exception
is caught or is declared in a throws clause.

Dr. Amal Khalifa, 2016


Java Exception Hierarchy
24

 An exception’s type determines whether it is checked or


unchecked.
 Direct or indirect subclasses of class
RuntimeException (package java.lang) are
unchecked exceptions.
 Typically caused by defects in your program’s code (e.g.,
ArrayIndexOutOfBoundsExceptions).
 Subclasses of Exception but not
RuntimeException are checked exceptions.
 Caused by conditions that are not in the control of the program—e.g., in file
processing, the program can’t open a file because the file does not exist.
 Classes that inherit from class Error are considered to be
unchecked.
Dr. Amal Khalifa, 2016
25 That’s all for today!!
Text Book ref.
Chapter 11.1  11.5

Dr. Amal Khalifa, 2016

You might also like