08 aggregation and collection classes

49
OOSSE - Java Lecture 7 1 May 28, 2022 Aggregation and Collection Classes OOSSE - Programming with Java Lecture 7

Upload: apu

Post on 26-May-2015

323 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 08  aggregation and collection classes

OOSSE - Java Lecture 7 1Apr 12, 2023

Aggregation and Collection Classes

OOSSE - Programming with JavaLecture 7

Page 2: 08  aggregation and collection classes

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

Page 3: 08  aggregation and collection classes

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

Page 4: 08  aggregation and collection classes

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

Page 5: 08  aggregation and collection classes

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

Page 6: 08  aggregation and collection classes

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

Page 7: 08  aggregation and collection classes

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; }

Page 8: 08  aggregation and collection classes

OOSSE - Java Lecture 7 8Apr 12, 2023

PersonalDetails

public String getFullname() { return Fullname; }

public String getEmail() { return email; }

public int getAge() { return age; }}

Page 9: 08  aggregation and collection classes

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; }

Page 10: 08  aggregation and collection classes

OOSSE - Java Lecture 7 10Apr 12, 2023

JobDescription (continued)

public String getTitle() { return title; }

String title; String department; int grade;}

Page 11: 08  aggregation and collection classes

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; }

Page 12: 08  aggregation and collection classes

OOSSE - Java Lecture 7 12Apr 12, 2023

Employee (continued)

public String toString()

{ String s = "Employee Details\n" +

lnkPersonalDetails.toString() + "\n" + lnkJobDescription.toString(); return s; }}

Page 13: 08  aggregation and collection classes

OOSSE - Java Lecture 7 13Apr 12, 2023

Employee

Page 14: 08  aggregation and collection classes

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); }}

Page 15: 08  aggregation and collection classes

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

Page 16: 08  aggregation and collection classes

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

Page 17: 08  aggregation and collection classes

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!

Page 18: 08  aggregation and collection classes

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

Page 19: 08  aggregation and collection classes

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

Page 20: 08  aggregation and collection classes

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

Page 21: 08  aggregation and collection classes

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

Page 22: 08  aggregation and collection classes

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

Page 23: 08  aggregation and collection classes

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

Page 24: 08  aggregation and collection classes

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 *

Page 25: 08  aggregation and collection classes

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 *

Page 26: 08  aggregation and collection classes

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[] ;…

Page 27: 08  aggregation and collection classes

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

Page 28: 08  aggregation and collection classes

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; }

Page 29: 08  aggregation and collection classes

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; }}

Page 30: 08  aggregation and collection classes

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]; }

Page 31: 08  aggregation and collection classes

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; } }

Page 32: 08  aggregation and collection classes

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]); } }}

Page 33: 08  aggregation and collection classes

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(); }}

Page 34: 08  aggregation and collection classes

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)

Page 35: 08  aggregation and collection classes

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

Page 36: 08  aggregation and collection classes

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 ) …

Page 37: 08  aggregation and collection classes

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 )

Page 38: 08  aggregation and collection classes

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) ; }

Page 39: 08  aggregation and collection classes

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; } }

Page 40: 08  aggregation and collection classes

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)); } }

Page 41: 08  aggregation and collection classes

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); } } }}

Page 42: 08  aggregation and collection classes

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

Page 43: 08  aggregation and collection classes

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); } }

Page 44: 08  aggregation and collection classes

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);

Page 45: 08  aggregation and collection classes

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

Page 46: 08  aggregation and collection classes

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

Page 47: 08  aggregation and collection classes

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

Page 48: 08  aggregation and collection classes

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

Page 49: 08  aggregation and collection classes

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