1 / 40

Prof. Dr. Max Mühlhäuser Dr. Guido Rößling

Introduction to Computer Science I Topic 15: Class properties, access rights and Collections. Prof. Dr. Max Mühlhäuser Dr. Guido Rößling. Structure of this lecture. Class properties Access privileges Collections (Arrays and collection types). Class Properties.

ashtyn
Download Presentation

Prof. Dr. Max Mühlhäuser Dr. Guido Rößling

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to Computer Science ITopic 15: Class properties, access rights and Collections Prof. Dr. Max Mühlhäuser Dr. Guido Rößling

  2. Structure of this lecture • Class properties • Access privileges • Collections (Arrays and collection types)

  3. Class Properties • Some properties should be shared by all instancesof a class: • A counter stores how many instances of a class were created • The next unique identification for an instance (e.g., customer number) • Constants which may be useful to all objects • Class attributesand class methods are features associated with the class itself (not its objects)

  4. Class Properties • Class features are declared with the keyword static • Access with <Class>.<Identifier> • Within the class, one may omit the class name • They may be accessed from anywhere the class is visible • Known examples • Class attribute: System.out • Class method: public static void main(...)

  5. static variable only exists once for all objects initializationoccurs before any method is executed Upon creation of a new person, the counter is updated Class Properties class Person { static int personCount = 0; Person( .. ) { personCount++; // ... } //...

  6. Class Properties // class Person (continued) // ... static int personCount() { return personCount; } //... Retrieve the number of existing person objects

  7. receiver compared withanother circle object compares two circles Class Properties • Access via class name int count = Person.personCount(); System.out.println(count +" objects"); • Another typical application booleanisLargerThan(Circle b) { .. } static booleanisLargerThan(Circle a, Circle b) {..}

  8. Class Properties Class methods may not access instance features class Mistake { int i; static void main() { something(i); // … } } Not possible unless an object is created or "i" is a class variable

  9. Class Properties Static Initialization <Static-Initializer> ::= static { <Statements> } • Purpose: initializationof class attributes • Similar to constructors for objects • Useful if simple initialization is insufficient

  10. Class Properties execution upon loading the class definition Static Initialization publicclassInitializationExample { private staticdouble[] vector = new double[6]; // staticinitialization block static{ for(int i = 0; i < vector.length; i++) { vector[i] = 1.0 / (i + 1); } } // ... }

  11. Constants • May only receive a value once • after that, read access only => immutable • Constants are declared like variables but using the keyword final • private final int MAXIMUM_NUMBER_CARDS = 5; • A constant declaration mustalways have an initialization part • Convention: capital letters using underscores to separate words

  12. Structure of this lecture • Class properties • Access privileges • Collections (Arrays and collection types)

  13. Access Privileges • Features are declared with their intended visibility • <Modifier> ::= private | ε | protected| public • with the help of visibility modifiers one can determine which clients may access an attribute, method or class • Four levels of visibility • hidden elements (private) • package elements (no modifier) • internal elements (protected) • freely accessible elements (public)

  14. Access Privileges private • Access possible only from within the class itself • package(implicit; no modifier given) • The class element is visible for all classes in the same package • No access from outside the package is allowed • Not even from heirs in another package! • Package as a collection of classes which “trust" each other, have high cohesion

  15. Access Privileges protected • All classes in the same package may access the element • Same for all heirs of the class (even if in a different package) • Heirs as "trusted" clients are allowed to access implementation details of the ancestor • public • Any class may access the element

  16. Access Privileges Overview private package protected public Heirs inother packages Classes in otherpackages Same class Samepackage Heirs insamepackage Have the same access rights

  17. Access Privileges package A; class AC extends AA { // one, two, three } package A; publicclass AA { publicint one; protectedint two; void three() { … } privatevoid four() { … } } package B; class BA extends AA { // one, two } package A; class AB { // one, two, three } package B; class BB { // one }

  18. Access Privileges Class Modifiers • Either public • Unique—worldwide • Only one class may be specified public per file • Filename must be ClassName + “.java” • or implicit(no keyword given) • Only visible within the same package

  19. Access Privileges Modifiers and Redefinition • If a method is redefined, its visibility may only be extended • Reason: substitutability • It must be possible to substitute an object of a more special type for an object of a more general type • The subclass must offer at least as many features as its ancestor • It must not hide redefined features from clients

  20. Class -privateAttribute : AnotherClass #protectedAttribute : int +publicMethod(x: int) : boolean Access Privileges Visibility using UML • UML offers "public", "protected" and "private" • public+ • protected# • private- • no modifier  visibility is undefined

  21. Structure of this lecture • Class properties • Access privileges • Collections (Arrays and collection types)

  22. Collection Types • A frequently needed kind of data structure is a collection for storing multiple data items • either of exactly the same type • or of the same type (including subtypes) • or of various types (i.e., of type Object) • Depending on intended use, the collections types… • support quick access to individual elements • provide support for keeping elements sorted • provide a discipline for accessing certain elements only • may grow on demand • etc.

  23. Wrapper Classes • Primitivedatatypes are not reference types • Are not derived from Object, can not respond to messages • Can not be assigned to variables of type Object • Sometimes it is useful (e.g., for collections) to treat a primitive piece of data as if it were an object Wrapper Classes Values versus References

  24. Wrapper Classes • Class name is derived from primitive data type, using a capital first letter • java.lang.Byte, java.lang.Short, java.lang.Integer, java.lang.Long, java.lang.Float, java.lang.Double, java.lang.Character • Wrapper objects are immutable • Value assignment happens via constructor • Value inquiry uses a message <primitiveType>Value()

  25. Autoboxing - Autounboxing • Since Java 1.5, an implicit conversion from int to Integer is possible (same for other types) // AUTOBOXING Integer a = 5; // AUTO-UNBOXING int i = a; Integer a = new Integer(5); int i = a.intValue();

  26. Collections Java offers a number of collection types, implementing the java.util.Collection interface, or one of the following sub-interfaces thereof (this list is incomplete!): • Collection • A general interface for collections of objects • No restrictions/guarantees regarding duplicates/ordering/sorting, etc. • List (has implementations ArrayList, LinkedList, Vector) • Objects are ordered • May contain duplicates • Enables direct access to objects via an index • Set (has implementation HashSet) • Objects may be contained only once • SortedSet (has implementation TreeSet) • Same as Set but ordered, user may specify customcomparison strategy for elements Collection Set List SortedSet

  27. Collections: Lists • In the following, we will assume the use of a collection of type „E“ (for element); this type can be replaced by „appropriate“ types. • Details follow in the slide set about Generics • The interface java.util.List contains these methods: • boolean add(E e) • Appends element e to the list • void add(int pos, E e) • Adds element e to the list at position pos; moves all succeeding elements back by one position • boolean addAll(Collection c) • Appends all elements stored in collection c to the list • boolean addAll(int pos, Collection c) • Adds all elements of collection c to list, starting at position pos

  28. Collections: Lists • voidclear() • Removes all elements from the list • boolean contains(Object o) • Returns true if object o is contained in the list • boolean containsAll(Collection c) • Returns true if all objects contained in c belong to the list • E get(int pos) • Returns the element at position pos • int indexOf(Object o) • Returns the first position at which o occurs in the list, else -1. For the last position, use int lastIndexOf(Object o) • boolean isEmpty() • Returns true if the list is empty

  29. Collections: Lists • E remove(int pos) • Removes the element at position pos and returns it • boolean remove(Object O) • Tries to remove object o from the list; returns true if successful • int size() • Returns the number of elements stored in the list • Object[] toArray() • Returns an array containing all elements of the list • Constructors in the subclasses: • Parameterless • With a Collections as a parameter: copies all values into the list • Special cases (see the subtypes)

  30. Collections: Implementations of List • java.util.LinkedList • Adds the following methods (this is only a subset!): • void addFirst(E) • void addLast(E) • E getFirst() • E getLast() • java.util.ArrayList • Elements are stored in an array • New methods (selection): • voidensureCapacity(int minCapacity) – if the list can contain less than minCapacity elements, the array is adapted to grow • voidtrimToSize() – shrinks the array to the list size • New constructor: ArrayList(int initialCapacity) for the size

  31. Collections: Implementations of List • java.util.Vector: • Essentially identical to java.util.ArrayList ( array-based) • Accesses are synchronized • Avoids problems if two objects want to write or read/write at the same time • „Standard class“ for many applications • Constructors: • Vector() – creates a Vector of a default size • Vector(int c) – creates a Vector of size c • Vector(int c, int inc) – creates a Vector of size c; if this is not enough, the Vector will grow by “inc” elements each time • The last constructor is to be preferred • You should determine beforehand how many elements you expect!

  32. Collections: Set • A Set represents a mathematical set • Thus, a given object can be contained at most once • Also supports most of the methods we already know • boolean add(E e) • boolean addAll(Collection c) • void clear() • boolean contains(Object O) • boolean containsAll(Collection c) • boolean isEmpty() • boolean remove(Object O) • boolean removeAll(Collection c) • int size() • Object[] toArray() • Insertion fails if the set already contains the object

  33. Collections: Set • Concrete instances of Set: • java.util.HashSet: stores the data in a hash table (very efficient access) • java.util.TreeSet: stores the data in a tree with an access time of O(log n). • There are additional specialized implementations • Please check the JDK API Documentation!

  34. Interface Map Sometimes objects should not be accessible via a numeric index, but via a key (some unique, but otherwise arbitrary value) of some sort,e.g., access telephone number via "surname + name" • This is supported by the interface java.util.Map • … and its sub-interface SortedMap Map SortedMap

  35. Class: java.util.Hashtable • implementsjava.util.Map • Enables access to elements via a computed key, e.g., "surname + name“ • Key is first converted into a numeric index and then used for efficient access • Very efficient access • Theory of hashing in ICS II • Useful constructors • HashMap()default constructor • HashMap(int size)creates a HashMap of size size • HashMap(Map t)creates a HashMap, containing all elements contained in the map referenced by "t"

  36. Class java.util.Hashtable • Useful methods include • Object put(Object key, Object value)stores "value" for retrieval with "key" • Object get(Object key)retrieves object stored with "key" • boolean containsKey(Object key)answers whether an object is stored with "key" • boolean containsValue(Object value)answers whether "value" is stored in the table • Object remove(Object key)removes "key" and the object associated with it

  37. Iterators • Java uses an Iterator to step through the elements in a collection • Usually, you get the iterator by calling iterator() on the collection • This is true for all subclasses of the Collection interface • For a HashMap, retrieve the keys() first and then use iterator() • iterator() returns an instance of java.util.Iterator

  38. Iterators • The Iterator type offers only three operations: • boolean hasNext() – are there more elements? • Object next() – returns the next element, if there is one • Otherwise, a NoSuchElementException is thrown (see T18) • You should check first by using hasNext() • void remove() – removes the last retrieved element • May not be supported by all implementing types • In this case, you get a UnsupportedOperationException

  39. Iterators • Here is a practical example for using Iterators: • There is also a variant of the for loop for this purpose: • The loop uses an iterator to retrieve next() • This value is then assigned to o in each iteration • Usable for iterable elements – most collections, arrays List intList = Arrays.asList(1, 2, 3); // createlist int s = 0; for (Iteratorit = intList.iterator(); // getIterator it.hasNext(); ) // continuewhileelementsexist s += (Integer)it.next(); // addnextelementtosum for (Object o : intList) // get Iterator // continue while elements exist s += (Integer)o; // add next element to sum

  40. Collection Framework • Due to the extent of this subject, and our limited time, we could only partially cover it • Find out more on collections athttp://java.sun.com/docs/books/tutorial/collections/index.html • Several specialized classes are available • Before implementing a type yourself, check http://java.sun.com/javase/6/docs/technotes/guides/collections/index.html

More Related