SlideShare a Scribd company logo
Aggregation and Collection Classes


               OOSSE - Programming with Java
                         Lecture 7




Dec 21, 2012    OOSSE - Java Lecture 7     1
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




Dec 21, 2012   OOSSE - Java Lecture 7        2
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




Dec 21, 2012     OOSSE - Java Lecture 7            3
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




Dec 21, 2012      OOSSE - Java Lecture 7            4
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




Dec 21, 2012      OOSSE - Java Lecture 7             5
An Employee Class
 • The employee class
     – Has a employee number
     – Has a set of personal details
     – Has a job description




Dec 21, 2012       OOSSE - Java Lecture 7   6
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
PersonalDetails
     public String getFullname()
     {
       return Fullname;
     }

     public String getEmail()
     {
       return email;
     }

     public int getAge()
     {
       return age;
     }
 }




Dec 21, 2012          OOSSE - Java Lecture 7   8
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
JobDescription (continued)
     public String getTitle()
     {
       return title;
     }

     String title;
     String department;
     int grade;
 }




Dec 21, 2012         OOSSE - Java Lecture 7   10
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
Employee (continued)
     public String toString()
     {
       String s = "Employee Detailsn" +
                      lnkPersonalDetails.toString() + "n" +
                  lnkJobDescription.toString();
       return s;
     }
 }




Dec 21, 2012          OOSSE - Java Lecture 7                   12
Employee




Dec 21, 2012   OOSSE - Java Lecture 7   13
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
TestEmployee
 • The output from the test would be:

     Employee Details
     Fullname: Fred Bloggs age: 34 email: fred@xyz
     Job title: Plumber Grade: 3 Department: maintenance




Dec 21, 2012    OOSSE - Java Lecture 7        15
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




Dec 21, 2012     OOSSE - Java Lecture 7         16
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
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




Dec 21, 2012    OOSSE - Java Lecture 7           18
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

Dec 21, 2012    OOSSE - Java Lecture 7          19
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


Dec 21, 2012      OOSSE - Java Lecture 7             20
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


Dec 21, 2012      OOSSE - Java Lecture 7           21
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



Dec 21, 2012      OOSSE - Java Lecture 7            22
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




Dec 21, 2012      OOSSE - Java Lecture 7       23
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
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
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
Team Example
 • In this example a class is used to represent a team of players




                                Note how together indicates the aggregation



Dec 21, 2012      OOSSE - Java Lecture 7                 27
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
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
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
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
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
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
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
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


Dec 21, 2012      OOSSE - Java Lecture 7            35
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
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
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
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
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
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);
           }
        }
     }
 }
Dec 21, 2012          OOSSE - Java Lecture 7                  41
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



Dec 21, 2012      OOSSE - Java Lecture 7             42
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
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
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



Dec 21, 2012       OOSSE - Java Lecture 7              45
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


Dec 21, 2012             OOSSE - Java Lecture 7                            46
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.html
Dec 21, 2012                OOSSE - Java Lecture 7                            47
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




Dec 21, 2012       OOSSE - Java Lecture 7             48
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




Dec 21, 2012    OOSSE - Java Lecture 7         49

More Related Content

What's hot

Introduction to OOP(in java) BY Govind Singh
Introduction to OOP(in java)  BY Govind SinghIntroduction to OOP(in java)  BY Govind Singh
Introduction to OOP(in java) BY Govind Singh
prabhat engineering college
 
How to write you first class in c++ object oriented programming
How to write you first class in c++ object oriented programmingHow to write you first class in c++ object oriented programming
How to write you first class in c++ object oriented programming
Syed Faizan Hassan
 
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Sagar Verma
 
0 E158 C10d01
0 E158 C10d010 E158 C10d01
0 E158 C10d01
nikeshhayaran
 
4 Classes & Objects
4 Classes & Objects4 Classes & Objects
4 Classes & Objects
Praveen M Jigajinni
 
Classes and objects in c++
Classes and objects in c++Classes and objects in c++
Classes and objects in c++
Rokonuzzaman Rony
 
class c++
class c++class c++
class c++
vinay chauhan
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
Shailendra Veeru
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
Kasun Ranga Wijeweera
 
Xml session08
Xml session08Xml session08
Xml session08
Niit Care
 
Kick Start Jpa
Kick Start JpaKick Start Jpa
Kick Start Jpa
Stephan Janssen
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
Nilesh Dalvi
 
Class and object in c++
Class and object in c++Class and object in c++
Class and object in c++
NainaKhan28
 
Euclideus_Language
Euclideus_LanguageEuclideus_Language
Euclideus_Language
Justin Gagnon
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
rprajat007
 
C++ And Object in lecture3
C++  And Object in lecture3C++  And Object in lecture3
C++ And Object in lecture3
UniSoftCorner Pvt Ltd India.
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
backdoor
 
Introduction to java programming
Introduction to java programmingIntroduction to java programming
Introduction to java programming
shinyduela
 

What's hot (18)

Introduction to OOP(in java) BY Govind Singh
Introduction to OOP(in java)  BY Govind SinghIntroduction to OOP(in java)  BY Govind Singh
Introduction to OOP(in java) BY Govind Singh
 
How to write you first class in c++ object oriented programming
How to write you first class in c++ object oriented programmingHow to write you first class in c++ object oriented programming
How to write you first class in c++ object oriented programming
 
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
 
0 E158 C10d01
0 E158 C10d010 E158 C10d01
0 E158 C10d01
 
4 Classes & Objects
4 Classes & Objects4 Classes & Objects
4 Classes & Objects
 
Classes and objects in c++
Classes and objects in c++Classes and objects in c++
Classes and objects in c++
 
class c++
class c++class c++
class c++
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Xml session08
Xml session08Xml session08
Xml session08
 
Kick Start Jpa
Kick Start JpaKick Start Jpa
Kick Start Jpa
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Class and object in c++
Class and object in c++Class and object in c++
Class and object in c++
 
Euclideus_Language
Euclideus_LanguageEuclideus_Language
Euclideus_Language
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
C++ And Object in lecture3
C++  And Object in lecture3C++  And Object in lecture3
C++ And Object in lecture3
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Introduction to java programming
Introduction to java programmingIntroduction to java programming
Introduction to java programming
 

Similar to 08 aggregation and collection classes

L02 Software Design
L02 Software DesignL02 Software Design
L02 Software Design
Ólafur Andri Ragnarsson
 
C# by Zaheer Abbas Aghani
C# by Zaheer Abbas AghaniC# by Zaheer Abbas Aghani
C# by Zaheer Abbas Aghani
Information Technology Center
 
C# by Zaheer Abbas Aghani
C# by Zaheer Abbas AghaniC# by Zaheer Abbas Aghani
C# by Zaheer Abbas Aghani
Information Technology Center
 
oodb.ppt
oodb.pptoodb.ppt
oodb.ppt
ISHAAGARWAL75
 
09 abstract classesandinterfaces
09 abstract classesandinterfaces09 abstract classesandinterfaces
09 abstract classesandinterfaces
APU
 
2 rel-algebra
2 rel-algebra2 rel-algebra
2 rel-algebra
Mahesh Jeedimalla
 
Chapter 6 OOP (Revision)
Chapter 6 OOP (Revision)Chapter 6 OOP (Revision)
Chapter 6 OOP (Revision)
OUM SAOKOSAL
 
OOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and ObjectOOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and Object
dkpawar
 
UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptx
akila m
 
Adbms 15 object data management group
Adbms 15 object data management groupAdbms 15 object data management group
Adbms 15 object data management group
Vaibhav Khanna
 
02 introductionto java
02 introductionto java02 introductionto java
02 introductionto java
APU
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
talha ijaz
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
mha4
 
Adv DB - Full Handout.pdf
Adv DB - Full Handout.pdfAdv DB - Full Handout.pdf
Adv DB - Full Handout.pdf
3BRBoruMedia
 
introduction_OO.pptx
introduction_OO.pptxintroduction_OO.pptx
introduction_OO.pptx
MonishaAb1
 
unit 1 full ppt.pptx
unit 1 full ppt.pptxunit 1 full ppt.pptx
unit 1 full ppt.pptx
thenmozhip8
 
introduction_OO.pptx
introduction_OO.pptxintroduction_OO.pptx
introduction_OO.pptx
RohitRoy210643
 
Lecture01 object oriented-programming
Lecture01 object oriented-programmingLecture01 object oriented-programming
Lecture01 object oriented-programming
Hariz Mustafa
 
Seng 123 8-ooad
Seng 123 8-ooadSeng 123 8-ooad
Seng 123 8-ooad
Atilla Elçi
 
Adbms 17 object query language
Adbms 17 object query languageAdbms 17 object query language
Adbms 17 object query language
Vaibhav Khanna
 

Similar to 08 aggregation and collection classes (20)

L02 Software Design
L02 Software DesignL02 Software Design
L02 Software Design
 
C# by Zaheer Abbas Aghani
C# by Zaheer Abbas AghaniC# by Zaheer Abbas Aghani
C# by Zaheer Abbas Aghani
 
C# by Zaheer Abbas Aghani
C# by Zaheer Abbas AghaniC# by Zaheer Abbas Aghani
C# by Zaheer Abbas Aghani
 
oodb.ppt
oodb.pptoodb.ppt
oodb.ppt
 
09 abstract classesandinterfaces
09 abstract classesandinterfaces09 abstract classesandinterfaces
09 abstract classesandinterfaces
 
2 rel-algebra
2 rel-algebra2 rel-algebra
2 rel-algebra
 
Chapter 6 OOP (Revision)
Chapter 6 OOP (Revision)Chapter 6 OOP (Revision)
Chapter 6 OOP (Revision)
 
OOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and ObjectOOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and Object
 
UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptx
 
Adbms 15 object data management group
Adbms 15 object data management groupAdbms 15 object data management group
Adbms 15 object data management group
 
02 introductionto java
02 introductionto java02 introductionto java
02 introductionto java
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
Adv DB - Full Handout.pdf
Adv DB - Full Handout.pdfAdv DB - Full Handout.pdf
Adv DB - Full Handout.pdf
 
introduction_OO.pptx
introduction_OO.pptxintroduction_OO.pptx
introduction_OO.pptx
 
unit 1 full ppt.pptx
unit 1 full ppt.pptxunit 1 full ppt.pptx
unit 1 full ppt.pptx
 
introduction_OO.pptx
introduction_OO.pptxintroduction_OO.pptx
introduction_OO.pptx
 
Lecture01 object oriented-programming
Lecture01 object oriented-programmingLecture01 object oriented-programming
Lecture01 object oriented-programming
 
Seng 123 8-ooad
Seng 123 8-ooadSeng 123 8-ooad
Seng 123 8-ooad
 
Adbms 17 object query language
Adbms 17 object query languageAdbms 17 object query language
Adbms 17 object query language
 

More from APU

01 introduction to_module
01 introduction to_module01 introduction to_module
01 introduction to_module
APU
 
. 1. introduction to object orientation
. 1. introduction to object orientation. 1. introduction to object orientation
. 1. introduction to object orientationAPU
 
. 01 introduction_to_module
. 01 introduction_to_module. 01 introduction_to_module
. 01 introduction_to_moduleAPU
 
9. oo languages
9. oo languages9. oo languages
9. oo languages
APU
 
8. design patterns
8. design patterns8. design patterns
8. design patterns
APU
 
7. sequence and collaboration diagrams
7. sequence and collaboration diagrams7. sequence and collaboration diagrams
7. sequence and collaboration diagrams
APU
 
6. activity diagrams
6. activity diagrams6. activity diagrams
6. activity diagrams
APU
 
5. state diagrams
5. state diagrams5. state diagrams
5. state diagrams
APU
 
4. class diagrams using uml
4. class diagrams using uml4. class diagrams using uml
4. class diagrams using uml
APU
 
3. use cases
3. use cases3. use cases
3. use cases
APU
 
01 introduction to_module
01 introduction to_module01 introduction to_module
01 introduction to_module
APU
 
. 9. oo languages
. 9. oo languages. 9. oo languages
. 9. oo languagesAPU
 
. 8. design patterns
. 8. design patterns. 8. design patterns
. 8. design patternsAPU
 
. 5. state diagrams
. 5. state diagrams. 5. state diagrams
. 5. state diagramsAPU
 
. 4. class diagrams using uml
. 4. class diagrams using uml. 4. class diagrams using uml
. 4. class diagrams using umlAPU
 
. 2. introduction to uml
. 2. introduction to uml. 2. introduction to uml
. 2. introduction to umlAPU
 
. 01 introduction_to_module
. 01 introduction_to_module. 01 introduction_to_module
. 01 introduction_to_moduleAPU
 
14 file handling
14 file handling14 file handling
14 file handling
APU
 
13 gui development
13 gui development13 gui development
13 gui development
APU
 
10 exceptionsin java
10 exceptionsin java10 exceptionsin java
10 exceptionsin java
APU
 

More from APU (20)

01 introduction to_module
01 introduction to_module01 introduction to_module
01 introduction to_module
 
. 1. introduction to object orientation
. 1. introduction to object orientation. 1. introduction to object orientation
. 1. introduction to object orientation
 
. 01 introduction_to_module
. 01 introduction_to_module. 01 introduction_to_module
. 01 introduction_to_module
 
9. oo languages
9. oo languages9. oo languages
9. oo languages
 
8. design patterns
8. design patterns8. design patterns
8. design patterns
 
7. sequence and collaboration diagrams
7. sequence and collaboration diagrams7. sequence and collaboration diagrams
7. sequence and collaboration diagrams
 
6. activity diagrams
6. activity diagrams6. activity diagrams
6. activity diagrams
 
5. state diagrams
5. state diagrams5. state diagrams
5. state diagrams
 
4. class diagrams using uml
4. class diagrams using uml4. class diagrams using uml
4. class diagrams using uml
 
3. use cases
3. use cases3. use cases
3. use cases
 
01 introduction to_module
01 introduction to_module01 introduction to_module
01 introduction to_module
 
. 9. oo languages
. 9. oo languages. 9. oo languages
. 9. oo languages
 
. 8. design patterns
. 8. design patterns. 8. design patterns
. 8. design patterns
 
. 5. state diagrams
. 5. state diagrams. 5. state diagrams
. 5. state diagrams
 
. 4. class diagrams using uml
. 4. class diagrams using uml. 4. class diagrams using uml
. 4. class diagrams using uml
 
. 2. introduction to uml
. 2. introduction to uml. 2. introduction to uml
. 2. introduction to uml
 
. 01 introduction_to_module
. 01 introduction_to_module. 01 introduction_to_module
. 01 introduction_to_module
 
14 file handling
14 file handling14 file handling
14 file handling
 
13 gui development
13 gui development13 gui development
13 gui development
 
10 exceptionsin java
10 exceptionsin java10 exceptionsin java
10 exceptionsin java
 

08 aggregation and collection classes

  • 1. Aggregation and Collection Classes OOSSE - Programming with Java Lecture 7 Dec 21, 2012 OOSSE - Java Lecture 7 1
  • 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 Generics Dec 21, 2012 OOSSE - Java Lecture 7 2
  • 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 relationship Dec 21, 2012 OOSSE - Java Lecture 7 3
  • 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 class Dec 21, 2012 OOSSE - Java Lecture 7 4
  • 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, grade Dec 21, 2012 OOSSE - Java Lecture 7 5
  • 6. An Employee Class • The employee class – Has a employee number – Has a set of personal details – Has a job description Dec 21, 2012 OOSSE - Java Lecture 7 6
  • 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. 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. 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. JobDescription (continued) public String getTitle() { return title; } String title; String department; int grade; } Dec 21, 2012 OOSSE - Java Lecture 7 10
  • 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. 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. Employee Dec 21, 2012 OOSSE - Java Lecture 7 13
  • 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. TestEmployee • The output from the test would be: Employee Details Fullname: Fred Bloggs age: 34 email: fred@xyz Job title: Plumber Grade: 3 Department: maintenance Dec 21, 2012 OOSSE - Java Lecture 7 15
  • 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 approach Dec 21, 2012 OOSSE - Java Lecture 7 16
  • 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. 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 Dec 21, 2012 OOSSE - Java Lecture 7 18
  • 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 class Dec 21, 2012 OOSSE - Java Lecture 7 19
  • 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 class Dec 21, 2012 OOSSE - Java Lecture 7 20
  • 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 class Dec 21, 2012 OOSSE - Java Lecture 7 21
  • 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 employee Dec 21, 2012 OOSSE - Java Lecture 7 22
  • 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 collections Dec 21, 2012 OOSSE - Java Lecture 7 23
  • 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. 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. 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. Team Example • In this example a class is used to represent a team of players Note how together indicates the aggregation Dec 21, 2012 OOSSE - Java Lecture 7 27
  • 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. 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. 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. 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. 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. 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. 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. 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 Dec 21, 2012 OOSSE - Java Lecture 7 35
  • 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. 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. 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. 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. 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. 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); } } } } Dec 21, 2012 OOSSE - Java Lecture 7 41
  • 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 moves Dec 21, 2012 OOSSE - Java Lecture 7 42
  • 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. 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. 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 Dec 21, 2012 OOSSE - Java Lecture 7 45
  • 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.html Dec 21, 2012 OOSSE - Java Lecture 7 46
  • 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.html Dec 21, 2012 OOSSE - Java Lecture 7 47
  • 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 List Dec 21, 2012 OOSSE - Java Lecture 7 48
  • 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 Generics Dec 21, 2012 OOSSE - Java Lecture 7 49

Editor's Notes

  1. 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.