L18-ArraysObjects.ppt

Download Report

Transcript L18-ArraysObjects.ppt

King Fahd University of Petroleum & Minerals
College of Computer Science & Engineering
Information & Computer Science Department
ICS102
Lecture 19 : Arrays of Objects
Exercise

Implement a class Company with a list of
Employees. (the maximum number of Employees is
100)
 The class Company should have an array
of Employee objects as instance variable.
Array of objects example
Array of objects
(declaration)
Creation
Array of objects example

Write a method to add an employee to the Company
Array of objects example

Write a method to compute the total budget for all
salaries
A new version of class Employee

Consider this new version of class Employee
Class Date
Class Date
Class Date
A new version of class Employee

Consider this new version of class Employee
Do you see any problem?
This version has two serious
problems !!!
Problem 1
What will be printed here?
 The problem is in the constructor of class Employee
Correct version
Problem 2
What will be printed here?
 The problem is in the accessor getBirthDate which returns
a reference to Date object
Correct version
Is there a problem?

Does the same problem happens here?
What will be printed here?
There is no problem here!
Explanation .. Next slide ..
Mutable and Immutable Classes

A class that contains no methods (other than
constructors) that change any of the data in an object of
the class is called an immutable class



Objects of such a class are called immutable objects
It is perfectly safe to return a reference to an immutable
object because the object cannot be changed in any way
The String class is an immutable class
Mutable and Immutable Classes

A class that contains public mutator methods or other
public methods that can change the data in its objects is
called a mutable class, and its objects are called mutable
objects


Never write a method that returns a mutable object
Instead, use a copy constructor to return a reference to a
completely independent copy of the mutable object
Constant declaration

A constant is a variable whose value is set once and
cannot be changed anymore. Example:
Constant declaration
THE END
.. of ICS-102 !