08 aggregation and collection classes

620 views

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
620
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
11
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • Part of this lecture will be reserved for working through solutions to selected exercises from last week. Notes relating to this do not appear in the slides.
  • 08 aggregation and collection classes

    1. 1. Aggregation and Collection Classes OOSSE - Programming with Java Lecture 7Dec 21, 2012 OOSSE - Java Lecture 7 1
    2. 2. 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 GenericsDec 21, 2012 OOSSE - Java Lecture 7 2
    3. 3. 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 relationshipDec 21, 2012 OOSSE - Java Lecture 7 3
    4. 4. 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 classDec 21, 2012 OOSSE - Java Lecture 7 4
    5. 5. 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, gradeDec 21, 2012 OOSSE - Java Lecture 7 5
    6. 6. An Employee Class • The employee class – Has a employee number – Has a set of personal details – Has a job descriptionDec 21, 2012 OOSSE - Java Lecture 7 6
    7. 7. 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; }Dec 21, 2012 OOSSE - Java Lecture 7 7
    8. 8. PersonalDetails public String getFullname() { return Fullname; } public String getEmail() { return email; } public int getAge() { return age; } }Dec 21, 2012 OOSSE - Java Lecture 7 8
    9. 9. 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; }Dec 21, 2012 OOSSE - Java Lecture 7 9
    10. 10. JobDescription (continued) public String getTitle() { return title; } String title; String department; int grade; }Dec 21, 2012 OOSSE - Java Lecture 7 10
    11. 11. 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; }Dec 21, 2012 OOSSE - Java Lecture 7 11
    12. 12. Employee (continued) public String toString() { String s = "Employee Detailsn" + lnkPersonalDetails.toString() + "n" + lnkJobDescription.toString(); return s; } }Dec 21, 2012 OOSSE - Java Lecture 7 12
    13. 13. EmployeeDec 21, 2012 OOSSE - Java Lecture 7 13
    14. 14. 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); } }Dec 21, 2012 OOSSE - Java Lecture 7 14
    15. 15. TestEmployee • The output from the test would be: Employee Details Fullname: Fred Bloggs age: 34 email: fred@xyz Job title: Plumber Grade: 3 Department: maintenanceDec 21, 2012 OOSSE - Java Lecture 7 15
    16. 16. 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 approachDec 21, 2012 OOSSE - Java Lecture 7 16
    17. 17. 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!Dec 21, 2012 OOSSE - Java Lecture 7 17
    18. 18. 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 classDec 21, 2012 OOSSE - Java Lecture 7 18
    19. 19. 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 classDec 21, 2012 OOSSE - Java Lecture 7 19
    20. 20. 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 classDec 21, 2012 OOSSE - Java Lecture 7 20
    21. 21. 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 classDec 21, 2012 OOSSE - Java Lecture 7 21
    22. 22. 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 employeeDec 21, 2012 OOSSE - Java Lecture 7 22
    23. 23. 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 collectionsDec 21, 2012 OOSSE - Java Lecture 7 23
    24. 24. 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 *Dec 21, 2012 OOSSE - Java Lecture 7 24
    25. 25. 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 *Dec 21, 2012 OOSSE - Java Lecture 7 25
    26. 26. 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 Players public class Team { private Player thePlayers[] ; …Dec 21, 2012 OOSSE - Java Lecture 7 26
    27. 27. Team Example • In this example a class is used to represent a team of players Note how together indicates the aggregationDec 21, 2012 OOSSE - Java Lecture 7 27
    28. 28. 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; }Dec 21, 2012 OOSSE - Java Lecture 7 28
    29. 29. 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; } }Dec 21, 2012 OOSSE - Java Lecture 7 29
    30. 30. 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]; }Dec 21, 2012 OOSSE - Java Lecture 7 30
    31. 31. 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; } }Dec 21, 2012 OOSSE - Java Lecture 7 31
    32. 32. 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]); } } }Dec 21, 2012 OOSSE - Java Lecture 7 32
    33. 33. 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(); } }Dec 21, 2012 OOSSE - Java Lecture 7 33
    34. 34. 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)Dec 21, 2012 OOSSE - Java Lecture 7 34
    35. 35. 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 ObjectDec 21, 2012 OOSSE - Java Lecture 7 35
    36. 36. 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 ) …Dec 21, 2012 OOSSE - Java Lecture 7 36
    37. 37. Vector Methods • Vector contains many methods including: – capacity( ) – size ( ) – firstElement( ) – lastElement( ) – isEmpty – removeAllElements( ) – removeElement( int index ) – indexOf ( Object element )Dec 21, 2012 OOSSE - Java Lecture 7 37
    38. 38. 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) ; }Dec 21, 2012 OOSSE - Java Lecture 7 38
    39. 39. 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; } }Dec 21, 2012 OOSSE - Java Lecture 7 39
    40. 40. 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)); } }Dec 21, 2012 OOSSE - Java Lecture 7 40
    41. 41. 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 players 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); } } } }Dec 21, 2012 OOSSE - Java Lecture 7 41
    42. 42. 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 movesDec 21, 2012 OOSSE - Java Lecture 7 42
    43. 43. 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); } }Dec 21, 2012 OOSSE - Java Lecture 7 43
    44. 44. 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);Dec 21, 2012 OOSSE - Java Lecture 7 44
    45. 45. 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 recompiledDec 21, 2012 OOSSE - Java Lecture 7 45
    46. 46. 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.htmlDec 21, 2012 OOSSE - Java Lecture 7 46
    47. 47. Implementations • General-purpose Implementations: Interfaces Implementations Resizable Hash table Tree Linked list Hash table + Linked list array Set HashSet TreeSet LinkedHashSet List ArrayList LinkedList Queue Map HashMap TreeMap LinkedHashMap • Taken from: http://java.sun.com/docs/books/tutorial/collections/index.htmlDec 21, 2012 OOSSE - Java Lecture 7 47
    48. 48. 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 ListDec 21, 2012 OOSSE - Java Lecture 7 48
    49. 49. 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 GenericsDec 21, 2012 OOSSE - Java Lecture 7 49

    ×