08 aggregation and collection classes
TRANSCRIPT
OOSSE - Java Lecture 7 1Apr 12, 2023
Aggregation and Collection Classes
OOSSE - Programming with JavaLecture 7
OOSSE - Java Lecture 7 2Apr 12, 2023
Objectives
In this lecture, we will:• Discuss the Has-A relationship• Define classes that contain instances of other
classes• Introduce concept of ownership of objects• Review the UML class diagrams used to indicate
the Has-A relationship• Introduce Collections and the Java Collections API• Discuss Generics
OOSSE - Java Lecture 7 3Apr 12, 2023
The HAS-A Relationship
• The classes that we have built so far represent fairly simple objects– the member variables are instances of simple data
types
• The approach in OOP is a building block approach• Once we have built simple classes these can be
used as the basis of more complicated classes• The simplest relationship is where a new class has
member variables that are instances of other classes– the HAS-A relationship
OOSSE - Java Lecture 7 4Apr 12, 2023
The HAS-A Relationship
• A class is used to model and encapsulate an object• Member variables represent the attributes of an
object• In a complex model the attributes may themselves
be objects rather than primitive data types• Consider modelling a vehicle, we may think of the
components as objects– a vehicle has wheels; the wheels are objects– a vehicle has an engine; the engine is an object
• The term HAS-A is used to describe the relationship between the vehicle class and the engine class
OOSSE - Java Lecture 7 5Apr 12, 2023
An Employee Class
• In modelling an employee we may start with a class that has the following member variables:– a payroll number, a set of personal details, a job
description
• The set of personal details may be best modelled using another class that has member variables such as:– name, age, email
• The job description may be another class with member variables such as:– title, department, grade
OOSSE - Java Lecture 7 6Apr 12, 2023
An Employee Class
• The employee class– Has a employee number– Has a set of personal
details– Has a job description
OOSSE - Java Lecture 7 7Apr 12, 2023
PersonalDetails
public class PersonalDetails { private String Fullname; private int age; private String email;
public PersonalDetails(String n, int a, String e) { Fullname = n; age = a; email = e; } public String toString() { String s = "Fullname: " + Fullname + " age: " + age + " email: " + email; return s; }
OOSSE - Java Lecture 7 8Apr 12, 2023
PersonalDetails
public String getFullname() { return Fullname; }
public String getEmail() { return email; }
public int getAge() { return age; }}
OOSSE - Java Lecture 7 9Apr 12, 2023
JobDescription
public class JobDescription { public JobDescription(String t, String d, int g) { title = t; department = d; grade = g; }
public String toString() { String s = "Job title: " + title + " Grade: " + grade + " Department: " + department ; return s; }
OOSSE - Java Lecture 7 10Apr 12, 2023
JobDescription (continued)
public String getTitle() { return title; }
String title; String department; int grade;}
OOSSE - Java Lecture 7 11Apr 12, 2023
Employee
public class Employee { private int payrollNumber; private PersonalDetails lnkPersonalDetails; private JobDescription lnkJobDescription;
public Employee(PersonalDetails d, JobDescription j, int n)
{ lnkPersonalDetails = d; lnkJobDescription = j; payrollNumber = n; }
OOSSE - Java Lecture 7 12Apr 12, 2023
Employee (continued)
public String toString()
{ String s = "Employee Details\n" +
lnkPersonalDetails.toString() + "\n" + lnkJobDescription.toString(); return s; }}
OOSSE - Java Lecture 7 13Apr 12, 2023
Employee
OOSSE - Java Lecture 7 14Apr 12, 2023
TestEmployee
public class TestEmployee { // Driver class used to test the Employee class public static void main(String [ ] args) {
PersonalDetails fredPD = new PersonalDetails("Fred Bloggs", 34, "fred@xyz");
JobDescription fredJD = new JobDescription("Plumber", "maintenance",3);
Employee fred = new Employee(fredPD,fredJD,1001); System.out.println(fred); }}
OOSSE - Java Lecture 7 15Apr 12, 2023
TestEmployee
• The output from the test would be:
Employee DetailsFullname: Fred Bloggs age: 34 email: fred@xyzJob title: Plumber Grade: 3 Department:
maintenance
OOSSE - Java Lecture 7 16Apr 12, 2023
Encapsulation and the HAS-A Relationship• Consider a class that contains member variables
that are instances of other classes• How is access to the functionality of the contained
classes exposed to users of the containing class?• Option 1 - make the member variables public
giving direct access to the public members of the contained classes– Breaks encapsulation
• Option 2 - make the member variables private and write wrapper functions that call the member functions of the contained classes– A more object oriented approach
OOSSE - Java Lecture 7 17Apr 12, 2023
Exposing the Name of an Employee
• Suppose the name of an employee is required• How can a method to provide the name of an
employee be written?• The name is stored in the PersonalDetails object
– private String Fullname– Accessible using the getFullname() method
• Employee can be considered as a wrapper class that takes advantage of the functionality in PersonalDetails– The user of the Employee class does not need to
know that an object of type PersonalDetails is used– Indeed a user of Employee should not have to know!
OOSSE - Java Lecture 7 18Apr 12, 2023
The name of an Employee
• Consider the following code :
public String getName() { // delegate to the PersonalDetails object return lnkPersonalDetails.getFullname(); }
• This is a method of the Employee class
OOSSE - Java Lecture 7 19Apr 12, 2023
The name and Job of an Employee
• Suppose the name and job title of an employee are required as a string
public String getNameAndJob () { // use methods of PersonalDetails and JobDescription String s = getName() + " " +
lnkJobDescription.getTitle(); return s; }
• This is a method of the employee class
OOSSE - Java Lecture 7 20Apr 12, 2023
Constructors Revisited
• Consider the constructor of an Employee:
public Employee(PersonalDetails d, JobDescription j, int n)
{ lnkPersonalDetails = d; lnkJobDescription = j; payrollNumber = n; }
• The constructor receives two objects and an integer– The details and job description are constructed
outside of the employee class
OOSSE - Java Lecture 7 21Apr 12, 2023
An Alternative Constructor
public Employee(String n, int a, String e, String t, String d, int g, int num) { lnkPersonalDetails = new PersonalDetails(n,a,e); lnkJobDescription = new JobDescription(t,d,g);
payrollNumber = num; }
• In this version the objects representing the details and job are constructed inside the employee class
• Constructors and other methods can be overloaded – both versions can exist in the same class
OOSSE - Java Lecture 7 22Apr 12, 2023
Ownership
• Which of the two versions of the constructor is the right one to choose?
• This is a design issue• In the first example the employee does not own the
objects that describe the personal details and the job– The employee is not responsible for their construction
• In the second example the employee owns the objects– The objects were constructed inside the Employee class
• The design decision is based upon whether or not the objects that describe the personal details and the job NEED to exist outside of an employee
OOSSE - Java Lecture 7 23Apr 12, 2023
What next?
• We have seen a class to represent an employee that contains instances of other classes– has-a relationship
• How do we go about storing and accessing a group of employees?
• We will now look at two possible ways of storing groups of objects:– using arrays– using collections
OOSSE - Java Lecture 7 24Apr 12, 2023
Aggregation
• Aggregation describes the case where an object of one class contains objects of another class– The Has-A relationship describe earlier
• Consider a team made up of several players:
Team Player
1 *
OOSSE - Java Lecture 7 25Apr 12, 2023
Composition
• Composition is a stronger form of aggregation– The contained objects do not have an existence
independent of the container– Construction of the objects is the responsibility of the
container
• Consider a house with several walls:
House Wall
1 *
OOSSE - Java Lecture 7 26Apr 12, 2023
Representing Aggregation
• The simplest way to represent a 1 to many aggregation is to use an array
• The container class manages the collection of objects – an array is used to hold the collection
• Arrays were introduced in an earlier lecture• Consider the team of players discussed earlier• The Team class might have a member variable that
is an array of Playerspublic class Team{
private Player thePlayers[] ;…
OOSSE - Java Lecture 7 27Apr 12, 2023
Team Example
• In this example a class is used to represent a team of players
Note how together indicates the aggregation
OOSSE - Java Lecture 7 28Apr 12, 2023
Player
public class Player { private String name; private String position; private int age;
public Player (String s, String p, int a) { name = s; position = p; age = a; }
OOSSE - Java Lecture 7 29Apr 12, 2023
Player (continued)
public String toString() { String s = "Name: " + name + " Position: " + position + " Age: " + age; return s; } public String getPosition() { return position; } public int getAge() { return age; }}
OOSSE - Java Lecture 7 30Apr 12, 2023
Team
public class Team { private Player [] thePlayers; private int numPlayers; private int maxPlayers; private String teamName; public Team (String name, int num) { teamName = name; maxPlayers = num; numPlayers = 0; thePlayers = new Player [maxPlayers]; }
OOSSE - Java Lecture 7 31Apr 12, 2023
Team (continued)
public boolean addPlayer( Player newPlayer ) { // add another player to the team if the team is not full if ( numPlayers == maxPlayers ) { // the team is full, player cannot be added return false; } else { // add player to the team thePlayers[numPlayers] = newPlayer; numPlayers++; return true; } }
OOSSE - Java Lecture 7 32Apr 12, 2023
Team (continued)
public void outputTeamDetails()
{ System.out.println("Team name: " + teamName ); //output each player in turn System.out.println("The players:"); for( int i=0; i < numPlayers; ++i) { System.out.println(thePlayers[i]); } }}
OOSSE - Java Lecture 7 33Apr 12, 2023
TestTeam
public class TestTeam { // Driver class to test the Team class public static void main(String []args) { //Construct a few players Player dave = new Player("Dave","Goalkeeper",24); Player joe = new Player("Joe", "Striker", 21); Player andy = new Player("Andy", "Defender", 29); Team rovers = new Team("Rovers",5); rovers.addPlayer(dave); rovers.addPlayer(joe); rovers.addPlayer(andy); rovers.outputTeamDetails(); }}
OOSSE - Java Lecture 7 34Apr 12, 2023
Collections
• Java supports several collection classes• The simplest to use is the vector
– the vector is like a dynamic array
• The vector class exists in the util namespace:– import java.util.*;
• Constructing a vector is easy:– Vector <Player> myVector = new Vector <Player> ()
;
• Here the initial size of the vector is not specified– the vector will grow as necessary
• The constructor is overloaded:– Vector <Player> (int size) – Vector <Player> (int size, int incr)
OOSSE - Java Lecture 7 35Apr 12, 2023
Using the Vector Class
• The capacity of the vector can be set to an initial value using the member function ensureCapacity– myVector.ensureCapacity(20);– Sets the minimum size of the vector to 20 items
• The method addElement can be used to add data to a vector:– Player andy = new Player("Andy", "Defender", 29);– myVector.addElement (andy);– inserts andy at the end of the current data
• Vectors hold Objects– Object is the base class of all objects– A player is an Object
OOSSE - Java Lecture 7 36Apr 12, 2023
Using the Vector Class
• The method elementAt can be used to get data out of the vector:– Player thePlayer;– thePlayer = myVector.elementAt(3) ;
• In older versions of Vector only Objects were held• An Object would be returned by the method• As it is known that Players are stored in the vector
then the object would be cast to a Player– Then the methods of the Player class can be used
• If objects of more than one type have been added to the vector then instanceof of could be used to check the type:– if ( myVector.elementAt(3) instanceof Player ) …
OOSSE - Java Lecture 7 37Apr 12, 2023
Vector Methods
• Vector contains many methods including:– capacity( ) – size ( )– firstElement( )– lastElement( )– isEmpty– removeAllElements( )– removeElement( int index )– indexOf ( Object element )
OOSSE - Java Lecture 7 38Apr 12, 2023
A Vector version of Team
import java.util.*;
public class VecTeam { private Vector <Player> thePlayers; private int numPlayers; private int maxPlayers; private String teamName; private Scanner kybd; public VecTeam (String name, int num) { teamName = name; maxPlayers = num; numPlayers = 0; thePlayers = new Vector <Player> (maxPlayers);
kybd = new Scanner (System.in) ; }
OOSSE - Java Lecture 7 39Apr 12, 2023
VecTeam
public boolean addPlayer( Player newPlayer ) { // add another player to the team if ( numPlayers == maxPlayers ) // the team is full {
return false; } else { // add player to the team thePlayers.addElement(newPlayer); numPlayers++; return true; } }
OOSSE - Java Lecture 7 40Apr 12, 2023
VecTeam (continued)
public void outputTeamDetails()
{ System.out.println("Team name: " + teamName ); //output each player in turn System.out.println("The players:"); for( int i=0; i < numPlayers; ++i) { System.out.println(thePlayers.elementAt(i)); } }
OOSSE - Java Lecture 7 41Apr 12, 2023
VecTeam (continued)
public void changePositions() { //output each player in turn and change position if required for( int i=0; i < numPlayers; ++i) { System.out.println(thePlayers.elementAt(i)); System.out.println(“Change the player's position?"); String ans = kybd.next(); if (ans.equals("yes")) {
System.out.print("Enter new position: "); String pos = kybd.next(); Player p = thePlayers.elementAt(i); p.setPosition(pos); } } }}
OOSSE - Java Lecture 7 42Apr 12, 2023
Iterators
• A collection is a set of data• Frequently it is useful to look at each item of data
in the collection in turn• An iterator is an object that is used to iterate
through the data items of a collection• Each collection provides an iterator of type Iterator• The method hasNext( ) can be used to test if the
collection has any more data• An iterator can be moved on to the next data item
in the collection using the method next( )– Next returns the object referred to before the iterator
moves
OOSSE - Java Lecture 7 43Apr 12, 2023
Using Iterators in the VecTeam class
public void outputTeamDetailsITR() { System.out.println("Team name: " + teamName ); //output each player in turn System.out.println("The players:"); Iterator itr = thePlayers.iterator(); while ( itr.hasNext() ) // while there are more
players { Player nextPlayer = (Player)itr.next(); System.out.println(nextPlayer); } }
OOSSE - Java Lecture 7 44Apr 12, 2023
Using Generic Types
• In the original versions of collections objects were stored– That is any object of any type could be added to a
collection– The collections were type unsafe
• With the release of JDK1.5 the generic types mechanism was introduced
• This allows the type of objects to be stored in a collection to be specified– The mechanism allows support for type checking at
compile time
• In the example using Vector earlier the generic type mechanism was used to store Person objects– Vetor <Person> thePlayers = new Vector <Person> (5);
OOSSE - Java Lecture 7 45Apr 12, 2023
Java Generics versus C++ Templates
• Generics and C++ templates are not the same!• Generics in Java provide compile time safety and
avoid the need for casts– Improved encapsulation– They use a technique known as type erasure– The compiler keeps track of generics internally– All instances use the same class file at compile/run
time
• In C++ a template is more like a powerful macro– Whenever a template class is instantiated with a new
class the entire code for the class is reproduced and recompiled
OOSSE - Java Lecture 7 46Apr 12, 2023
The Java Collections Framework
• The Java Collections Framework provides unified support for collections
• It contains:– Interfaces – Implementations– Algorithms
• The core collection interfaces:
• Taken from: http://java.sun.com/docs/books/tutorial/collections/index.html
OOSSE - Java Lecture 7 47Apr 12, 2023
Implementations
• General-purpose Implementations:
• Taken from: http://java.sun.com/docs/books/tutorial/collections/index.html
Interfaces Implementations
Hash tableResizable array
Tree Linked list Hash table + Linked list
Set HashSet TreeSet LinkedHashSet
List ArrayList LinkedList
Queue
Map HashMap TreeMap LinkedHashMap
OOSSE - Java Lecture 7 48Apr 12, 2023
Algorithms
• Algorithms provide re-useable code• For example there algorithms to provide the
following functionality:– Sorting– Shuffling– Searching
• The algorithms take the form of static methods in the Collections class– The first argument is the collection on which the
algorithm is to be carried out– Many of the algorithms operate on instances of List
OOSSE - Java Lecture 7 49Apr 12, 2023
Summary
In this lecture we have:• Discussed the Has-A relationship• Defined classes that contain instances of other
classes• Introduced concept of ownership of objects• Reviewed the UML class diagrams used to indicate
the Has-A relationship• Introduced Collections and the Java Collections API• Discussed Generics