Object-Oriented Programme 1 SSD3: Object-Oriented Programming and Design.

Презентация:



Advertisements
Похожие презентации
1/27 Chapter 9: Template Functions And Template Classes.
Advertisements

Unit II Constructor Cont… Destructor Default constructor.
© Luxoft Training 2013 Java Collections API. © Luxoft Training 2013 Collections hierarchy.
Loader Design Options Linkage Editors Dynamic Linking Bootstrap Loaders.
1 © Luxoft Training 2012 Inner and anonymous classes.
Inner Classes. 2 Simple Uses of Inner Classes Inner classes are classes defined within other classes The class that includes the inner class is called.
2005 Pearson Education, Inc. All rights reserved. 1 Object-Oriented Programming: Interface.
Java Collections Framework (JCF) in Java Tutorial for students of universities Author: Oxana Dudnik.
© 2005 Cisco Systems, Inc. All rights reserved. BGP v Route Selection Using Policy Controls Applying Route-Maps as BGP Filters.
Arrays Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig.
Sequences Sequences are patterns. Each pattern or number in a sequence is called a term. The number at the start is called the first term. The term-to-term.
Operator Overloading Customised behaviour of operators Chapter: 08 Lecture: 26 & 27 Date:
© 2009 Avaya Inc. All rights reserved.1 Chapter Two, Voic Pro Components Module Two – Actions, Variables & Conditions.
© 2006 Cisco Systems, Inc. All rights reserved. CVOICE v Configuring Voice Networks Configuring Dial Peers.
Object-Oriented Programme 1 SSD3: Object-Oriented Programming and Design.
© Luxoft Training 2013 Annotations. © Luxoft Training 2013 Java reflection / RTTI // given the name of a class, get a "Class" object that // has all info.
A class is just a collection of variables--often of different types--combined with a set of related functions. The variables in the class are referred.
PAT312, Section 21, December 2006 S21-1 Copyright 2007 MSC.Software Corporation SECTION 21 GROUPS.
Data Types in C. A Data Type A data type is –A set of values AND –A set of operations on those values A data type is used to –Identify the type of a variable.
1/30 Chapter 8: Dynamic Binding And Abstract classes.
Транксрипт:

Object-Oriented Programme 1 SSD3: Object-Oriented Programming and Design

Object-Oriented Programme Implementing Classes 2.2 Collections 2.3 Advanced Class Design Assessments Exam 2 Unit 2. Class Implementation

Object-Oriented Programme 3 Collections Collections Arrays ArrayList and Iterators Implementing the Collections of the Library System Assessments Practical Quiz 6 Practical Quiz 7 Multiple-Choice Quiz 4 Exercise 4

Object-Oriented Programme Arrays Arrays Declaring and Using Arrays Example Using Arrays

Object-Oriented Programme 5 Arrays Arrays An array is a homogeneous aggregate, a collection of data (each of which is the same type). In Java, an array can contain a set of primitives or a set of object references. Each item in an array is called an element. To access an element in an array, use the bracket operator ( [ ], ) and an integer index value that indicates the location of the element in the array. The first element in an array has an index of 0 the second has an index of 1, and so on. Consequently, the indexes in an array of n elements will range from 0 to n - 1. Array elements are stored contiguously in memory.

Object-Oriented Programme 6 Declaring and Using Arrays An array is declared by specifying the type of its elements, followed by [ ] : int[ ] ages; The type of the elements in the array is int. The name of the array is the identifier ages. String[ ] names; declares a String array, a collection of String references. The variables ages and names are reference variables and their values are initially null. null Each will remain null until an array object is created. (In Java, arrays are implemented as objects.)

Object-Oriented Programme 7 create an array object To create an array object, use the new operator, followed by the type of the elements and the arrays desired size. The array size must be non-negative interger. ages = new int[5]; names = new String[3]; When a new array object is created, its elements are initialized to their default values. the elements of the array ages are initialized to zero 0 the elements of the array names are initialized to null. null

Object-Oriented Programme 8 create an array object An array object contains a public instance variable called length indicates the number of elements in the array. the length of an array object can never change. However, an array reference can be changed so that it refers to another array object, with a different length. int[] values = new int[5]; int[] biggerArray = new int[10]; int nextIndex = 0;... if (nextIndex >= values.length) { values = biggerArray; }

Object-Oriented Programme 9 another way to create an array object the array declaration can include an initializer, a comma-separated list of initial element values within { }. An initializer can only be used in a declaration statement. int[] ages = {21, 19, 35, 27, 55}; String[] names = {"Bob", "Achebe", null}; The length of the array is deduced from the number of items in the initializer. jvm

Object-Oriented Programme 10 using array element ArrayIndexOutOfBoundsException an array element is accessed using the [ ] and an index. ages[2] // the third element, index 2 indicates the third element in the array: The Java Virtual Machine (JVM) will throw an ArrayIndexOutOfBoundsException if a program tries to use an invalid index. A negative index is always invalid. If an array contains n elements, then an index of n or greater is invalid. n

Object-Oriented Programme 11 using in for - loop Arrays are typically traversed in sequential order using for- loops. int[] values = new int[5]; for (int i = 0; i < values.length; ++i) { values[i] = i * i; } The loop control variable i serves two purposes in the loop body: 1. it is used as the array index and 2. it is used to calculate the value of each array element. 3. values.length is part of the loop termination condition.

Object-Oriented Programme 12 Example Using Arrays Sample code ( Dictionary.java)

Object-Oriented Programme 13 Note of sample code The words of the dictionary are stored in a String array. At line 77 the method addWord adds a word to the array. Initially, the array can hold up to five strings. If addWord is called and the array is full, addWord creates a new array (which is twice the size of the current array), copies the contents of the current array into the new array, and then updates the array reference so that it refers to the new array. At line 104 the method hasWord determines if the specified word is part of the dictionary. It searches the array linearly, beginning with the 0th element (that is, the first element at index 0). At line 33 the method main tests the implementation of class Dictionary using two arrays: knownWords and unknownWords. At line 42, the for-loop adds the strings in the array knownWords to the dictionary. At line 45, the for-loop verifies that the strings have been added to the dictionary. Finally, at line 52, the for-loop verifies that the strings in the array unknownWords are not part of the dictionary.

Object-Oriented Programme ArrayList and Iterators The ArrayList Class Iterators Using the For-Each Loop in Collections Implementing Collection Classes

Object-Oriented Programme 15 The ArrayList Class The class java.util.ArrayList implements a collection of objects that can grow to accommodate new items when the collection is full. The objects in the ArrayList can be accessed using an integer index.

Object-Oriented Programme 16 some of the methods defined in class ArrayList ArrayList() Constructs an empty collection. int size() Returns the number of objects in the collection. boolean isEmpty() Determines if there are no objects in the collection. boolean contains(Object elem) Determines if the specified object is an element of the collection (as determined by the method equals). boolean add(E o) Appends the specified object to the end of the collection. void add(int index, E element) Inserts the specified object at the specified index position, shifting any subsequent elements to the right (adds one to their indices).

Object-Oriented Programme 17 some of the methods defined in class ArrayList E get(int index) Returns the object at the specified position. public E set(int index, E element) Replaces the element at the specified index position with the specified object. public boolean remove(Object o) Removes the first occurrence of the specified object (using method equals), shifting any subsequent elements to the left (subtracts one from their indices). E remove(int index) Returns the object at the specified position after first removing it from the collection and shifting any subsequent elements to the left (subtracts one from their indices).

Object-Oriented Programme 18 Class ArrayList holds references to objects Class ArrayList holds references to objects of a particular data type. (not the object themselves) E.g., following segment of code creates a list of employees adds three employees to the list ArrayList employees = new ArrayList (); employees.add(new Employee("John Smith")); employees.add(new Employee("Mary Williams")); employees.add(new Employee("Peter Jefferson")); Employee firstEmployee = employees.get(0);

Object-Oriented Programme 19 collections can only hold object references collections can only hold object references rather than primitive types, primitive types must be placed in a wrapper object before they can be placed in a collection Integer in the case of int. E.g., illustrates how to use an ArrayList of integers: ArrayList numbers = new ArrayList (); numbers.add(1); // int num = numbers.get(0); Java has the ability to automatically box and unbox primitive data types, reducing the complexity to add and access primitive data types in the collections.

Object-Oriented Programme 20 Iterators Iterators The ArrayList method iterator() returns a java.util.Iterator object over the elements of the ArrayList. An iterator is an object for traversing a vector from start to finish. using iterators you can safely removing elements from the vector during the traversal.

Object-Oriented Programme 21 The class java.util.Iterator methods boolean hasNext(). HasSth...() Returns true if the iteration has more elements. E next(). Returns the next element in the iteration. void remove(). Removes from the collection the last element returned by the iterator. This method throws the exception IllegalStateException, if the next() has not been called, or the remove() has already been called after the last call to the next().

Object-Oriented Programme 22 Sample code code concatenates the strings in a collection and then displays the result: "ArrayList and Iterators". ArrayList list = new Arralist (); list.add("ArrayList"); list.add(" and "); list.add("Iterators"); String result = ""; for (Iterator listIterator = list.iterator(); listIterator.hasNext(); ) { result += listIterator.next(); } stdout.println(result);

Object-Oriented Programme 23 Sample Source code(DictionaryWithArrayList.java) The words of the dictionary are stored in an ArrayList collection. line 87 addWord() calls the ArrayList method add to add a word to the dictionary. line 100 hasWord() calls the ArrayList contains() to determine if the specified word is part of the dictionary. line 115 getStartsWith() uses an iterator to traverse the dictionary and returns an ArrayList with all words in the dictionary that start with the specified prefix. line 142 removeStartsWith() calls the Iterator method remove to remove a word from the dictionary.

Object-Oriented Programme 24 Using the For-Each Loop in Collections The for-each loop provides a simple way to iterate through the elements of a collection. In the for-each loop, you should specify the collection to iterate through, and a variable to access each element. code uses a for-each loop to concatenates the strings in a collection and then displays the result: "ArrayList and for- each". ArrayList list = new Arralist (); list.add("ArrayList"); list.add(" and "); list.add("for-each"); String result = ""; for (String element : list) { result += element; } stdout.println(result);

Object-Oriented Programme 25 note The for-each loop can be used only on those classes that implement the interface java.util.Iterable. An interface is a Java programming language construct that defines a group of methods that are implemented by a class. OOP To implement the interface Iterable, the class must include an implements clause in the class declaration, and declare the method iterator(). public class MyCollection implements Iterable {... public Iterator iterator() {... } The iterator() must return an Iterator object which is used to obtain the elements stored in the collection in a sequential order.

Object-Oriented Programme 26 Implementing Collection Classes a collection class models a one-to-many relationship. The one-to-many relationship can be implemented using an ArrayList to store the various instances in the collection. In addition, the class provides a set of methods to handle the collection.

Object-Oriented Programme 27 example the following class diagram represents a client with a collection of BankAccount instances.

Object-Oriented Programme 28 example The collection is stored in the Client attribute accounts. addAccount() stores an instance of class BankAccount in the collection. getAccountsIterator() returns an iterator over the bank accounts in the collection. getNumberOfBankAccounts() returns the number of bank accounts in the collection. Source code(Client.java, TestClient.java)

Object-Oriented Programme 29 NOTE The class Client uses an ArrayList to implement the collection of BankAccount objects. The class implements the interface Iterable provides the addAccount() to add a BankAccount object in the collection, and provides the iterator() to access the BankAccount objects stored in the collection.

Object-Oriented Programme Implementing the Collections of the Library System Library System Collection Classes Class Catalog Class BorrowedItems Class BorrowerDatabase Complete Library System

Object-Oriented Programme 31 Library System Collection Classes

Object-Oriented Programme 32 classes use collections The following classes use collections: Catalog BorrowedItems BorrowerDatabase

Object-Oriented Programme 33 Class Catalog The class Catalog uses a collection of CatalogItem instances. Instance variables: items. A ArrayList that contains references to CatalogItem instances. Constructor and methods: public Catalog(). Creates the vector items, which is initially empty. public void addItem(CatalogItem catalogItem). Adds the specified item to the catalog. public CatalogItem getItem(String code). Returns a reference to the CatalogItem instance with the specified code. Returns null if there are no items in the catalog with the specified code. public Iterator getItemsIterator(). Returns an iterator over the items in the catalog. public int getNumberOfItems(). Returns the number of items in the catalog. Source code ( Catalog.java)

Object-Oriented Programme 34 Class BorrowedItems The class BorrowedItems models the list of items checked out by a particular borrower. It uses a collection of CatalogItem instances. Instance variables: items. A ArrayList that contains references to CatalogItem instances. Constructor and methods: public BorrowedItems(). Creates the vector items, which is initially empty. public void addItem(CatalogItem catalogItem). Add the specified item to the list of items check out by the borrower. public CatalogItem getItem(String code). Returns a reference to the CatalogItem instance with the specified code. Returns null if there are no items in the list with the specified code. public Iterator getItemsIterator(). Returns an iterator over the borrowed items. public int getNumberOfItems(). Returns the number of borrowed items. Source code(BorrowedItems.java)

Object-Oriented Programme 35 Class BorrowerDatabase The class BorrowerDatabase models a database of borrowers. It uses a collection of Borrower instances. Instance variables: borrowers. A ArrayList that contains references to Borrower instances. Constructor and methods: public BorrowerDatabase(). Creates the vector borrowers, which is initially empty. public String addBorrower(Borrower borrower). Add the specified borrower to the database. public Borrower getBorrower(String id). Returns a reference to the Borrower instance with the specified id. Returns null if there are no borrowers in the database with the specified id. public Iterator getBorrowersIterator(). Returns an iterator over the borrowers in the database. public int getNumberOfItems(). Returns the number of borrowers in the database. Source code (BorrowerDatabase.java)

Object-Oriented Programme 36 Complete Library System The following files implement the other classes in the library system: Book.java Recording.java CatalogItem.java Borrower.java LibrarySystem.java