prof. dr. max mühlhäuser dr. guido rößling

40
Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 15: Class properties, access rights and Collections Prof. Dr. Max Mühlhäuser Dr. Guido Rößling

Upload: ashtyn

Post on 31-Jan-2016

26 views

Category:

Documents


0 download

DESCRIPTION

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. - PowerPoint PPT Presentation

TRANSCRIPT

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

Telecooperation/RBG

Technische Universität Darmstadt

Copyrighted material; for TUD student use only

Introduction to Computer Science ITopic 15: Class properties, access rights

and CollectionsProf. Dr. Max MühlhäuserDr. Guido Rößling

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

Structure of this lecture

• Class properties

• Access privileges

• Collections (Arrays and collection types)

2

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

Class Properties

• Some properties should be shared by all instances of 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 attributes and class methods are features associated with the class itself (not its objects)

3

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

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(...)

4

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

Class Properties

5

class Person {

static int personCount = 0;

Person( .. ) {

personCount++;

// ...

}

//...

initialization occurs before any method is executedinitialization occurs before any method is executed

static variable only exists once for all objects

static variable only exists once for all objects

Upon creation of a new person, the counter is updatedUpon creation of a new person, the counter is updated

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

Class Properties

// class Person (continued)

// ...

static int personCount() {

return personCount;

}

//...

6

Retrieve the number of existing person objects

Retrieve the number of existing person objects

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

Class Properties

• Access via class name int count = Person.personCount(); System.out.println(count +" objects");

• Another typical applicationboolean isLargerThan(Circle b) { .. }static boolean isLargerThan(Circle a, Circle b) {..}

7

compares two circlescompares two circles

receiver compared withanother circle objectreceiver compared withanother circle object

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

Class PropertiesClass methods may not

access instance features

8

class Mistake {

int i;

static void main() {

something(i);

// …

}

}

Not possible unless an objectis created or "i" is aclass variable

Not possible unless an objectis created or "i" is aclass variable

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

Class Properties

Static Initialization<Static-Initializer> ::= static { <Statements> }

• Purpose: initialization of class attributes• Similar to constructors for objects• Useful if simple initialization is insufficient

9

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

Class Properties

execution upon loading the class definition

10

public class InitializationExample { private static double[] vector

= new double[6]; // static initialization block static { for (int i = 0; i < vector.length; i++) { vector[i] = 1.0 / (i + 1); } } // ...}

public class InitializationExample { private static double[] vector

= new double[6]; // static initialization block static { for (int i = 0; i < vector.length; i++) { vector[i] = 1.0 / (i + 1); } } // ...}

Static Initialization

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

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 must always have an

initialization part– Convention: capital letters using underscores to

separate words

11

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

Structure of this lecture

• Class properties

• Access privileges

• Collections (Arrays and collection types)

12

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

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)

13

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

Access Privileges

private• Access possible only from within the class itself

14

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

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

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

15

public• Any class may access the element

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

Access Privileges

16

Sameclass

public

protected

package

private

Classes in other

packages

Heirs inother

packages

Samepackage

Heirs insame

package

Overview

Have the same access rights

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

Access Privileges

17

package A;public class AA {

public int one;protected int two;void three() { … }private void four() { … }

}

package A;public class AA {

public int one;protected int two;void three() { … }private void four() { … }

}

package B;class BA extends AA {

// one, two}

package B;class BA extends AA {

// one, two}

package A;class AB {

// one, two, three}

package A;class AB {

// one, two, three}

package B;class BB {

// one}

package B;class BB {

// one}

package A;class AC extends AA {

// one, two, three}

package A;class AC extends AA {

// one, two, three}

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

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

18

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

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

19

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

Access Privileges

Visibility using UML • UML offers "public", "protected" and "private"• public +• protected #• private -• no modifier visibility is undefined

20

Class

-privateAttribute : AnotherClass

#protectedAttribute : int

+publicMethod(x: int) : boolean

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

Structure of this lecture

• Class properties

• Access privileges

• Collections (Arrays and collection types)

21

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

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.

22

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

Wrapper Classes

• Primitive data types 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

23

Values versus References

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

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

24

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

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;

25

Integer a = new Integer(5);

int i = a.intValue();

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

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 custom

comparison strategy for elements

26

CollectionCollection

SortedSetSortedSet

SetSetListList

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

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

pos27

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

Collections: Lists• void clear()

– 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

28

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

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)

29

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

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

• void ensureCapacity(int minCapacity) – if the list can contain less than minCapacity elements, the array is adapted to grow

• void trimToSize() – shrinks the array to the list size

– New constructor: ArrayList(int initialCapacity) for the size

30

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

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!

31

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

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 object32

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

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!

33

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

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

34

MapMap

SortedMapSortedMap

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

Class: java.util.Hashtable• implements java.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"

35

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

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

36

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

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

37

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

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

38

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

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

39

List intList = Arrays.asList(1, 2, 3); // create listint s = 0; for (Iterator it = intList.iterator(); // get Iterator it.hasNext(); ) // continue while elements exist s += (Integer)it.next(); // add next element to sum

for (Object o : intList) // get Iterator // continue while elements exist s += (Integer)o; // add next element to sum

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

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T15

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

40