Advanced Java - bennedsen.orgbennedsen.org/java/repetition-slides - inked.pdf · Advanced Java Dr....

75
Advanced Java Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark [email protected]

Transcript of Advanced Java - bennedsen.orgbennedsen.org/java/repetition-slides - inked.pdf · Advanced Java Dr....

Advanced Java

Dr. Jens Bennedsen,

Aarhus University, School of Engineering

Aarhus, Denmark

[email protected]

Syllabus

Monday: Java overview

◦ Classes/Objects, Interfaces, Collections, Javadoc, …

Tuesday: Graphical User Interfaces (AWT/Swing)

◦ Events, Applets

Tuesday: Databases

Using data from a DB in a Java program

Wednesday: Threads

Doing more than one thing at a time

Thursday: Networks

◦ TCP/IP communication

JDBC 2

Slides etc

Slides etc avaliable at:

www.bennedsen.org/java

Advanced Java 3

Student response system

We will be using socrative:

Go to http://m.socrative.com (or

download it from Google play/appstore)

Join room 61710

Idea: Think – pair - share

Advanced Java 4

Socrative - test

Log on and answer the following:

”What is a class in Java?”

Advanced Java 5

History

Java was developed by Sun Microsystems

(now Oracle) and was initially released in

1995

◦ Originally called oak

Original design goals:

◦ Robust/reliable platform independent code

for electronic devises e.g. set-top boxes, VCRs,

telephones, ..

◦ Deal with problems associated with C++ like

memory leaks

6 Advanced Java

Java SE 8

Advanced Java 8

Elements of Java SE

Javac: Compile source code to byte-code

Java: execute Java programs

Javadoc: Generate (HTML) documentation

JPDA: Used by debyggers in development environments

Java Web start: Deploying applications

Java Plug-in: Execute Applets in web-browsers

AWT: Graphical user interface components

Swing: Improved graphical user interface components

Advanced Java 9

Advanced Java

Class

State

Behaviour

Attribute

Type

Constructor

Signature

Method

Return type

Parameter

Argument

Accessor

Mutator

Assignment

Advanced java

Class representing the concept

”Person”

public class Person {

private String name;

private int age;

public Person(String n, int a)

{ name= n; age= a; }

public void birthday()

{ age= age + 1; }

public int getAge()

{ return age; }

}

Behaviour

State

Advanced Java

State Attribute (field, variable)

◦ access modifier

◦ type

◦ value

Simple type

◦ int, boolean, ...

◦ 42, true, ...

Object type

◦ String, Date, Actor, ...

◦ ””, (1, 9, 2008), (”David”, 69)

variables

◦ primitive variable: variable that contains a value of the described type

◦ Object reference: variable that refers to an object of the described type

public class Person {

private String name;

private int age;

...

}

name

”David”

Object-reference

age 7

Simple variable

How many Person objecs are

created (1)?

A. 1

B. 2

C. 3

D. 4

E. 5

public static void main() {

Person peter = new Person("Peter", 42);

Person lisa = new Person("Lisa", 23);

Person susan = lisa;

susan.birthday();

System.out.println(lisa.getAge());

}

What is the output of the program

(1)?

A. 0

B. 23

C. 24

D. 42

E. 66 Advanced Java 16

public static void main() {

Person peter = new Person("Peter", 42);

Person lisa = new Person("Lisa", 23);

Person susan = lisa;

susan.birthday();

System.out.println(lisa.getAge());

}

Advanced Java

Encapsulation

Attributes

◦ The objects encapsulated state

◦ (often) declared private

◦ Can only be accessed by the methods in the class (of no concern to others)

Methods

◦ The objects facade (aka interface) to the outside

◦ (often) declared public

◦ Can be called from other classes

◦ signature: the heading of a method (access modifier, return type, name and parameters)

public class Person {

private String name;

private int age;

public Person(String n,

int a)

{ ... }

public void birthday()

{ ... }

public int getAge()

{ ... }

}

Naming Conventions

The following naming conventions should be used when writing Java programs ◦ Classes and Interfaces should begin with an UPPERcase

letter

◦ Variables, methods and object references should begin with a lowercase letter

◦ If more than one word, each internaleWord should start with an UPPERcase letter

Examples: ◦ Class: Car, Sensor, Observable, HashMap

◦ Interface: Observer, Map

◦ Method: add(objRef)

◦ Object reference: myObject

◦ Variable/attribute: myVar

Advanced Java 18

Exception: Constants are

represented by variables. They

are written with all

UPPERCASE LETTERS and

words seperated by

underscore, e.g. MY_CONST

Packages

Collections of classes that are related to a

common problem are grouped in a

package

Packages are represented by directories

Examples:

◦ The Java.util pacakage (corresponds to

the directory java/util

Advanced Java 19

Packages

If you want to use the functionality, you

need to import each class

◦ Except for the java.lang package which

are available by default

Example (use the Map interface and all

classes in java.awt)

Advanced Java 20

import java.util.Map;

import java.awt.*;

public class Test {

}

Additional packages

Other packages

◦ java.applet: Provides the classes necessary to create an applet and the classes an applet uses to communicate with its applet context.

◦ java.awt: Contains all of the classes for creating user interfaces and for painting graphics and images.

◦ java.net: Provides the classes for implementing networking applications.

◦ java.util: Contains the collections framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a random-number generator, and a bit array).

◦ javax.swing: Provides a set of "lightweight" (all-Java language) components that, to the maximum degree possible, work the same on all platforms.

◦ java.sql: Classes to manipulate databases

◦ …

Advanced Java 21

Javadoc

javadoc: The program to generate java

code documentation.

Input: Java source files (.java)

◦ Individual source files

◦ Root directory of the source files

Output: HTML files documenting

specification of java code

◦ One file for each class defined

◦ Package and overview files

Advanced Java 22

Javadoc source code

Advanced Java 23

Generated javadoc

Advanced Java 24

Inheritance

It is possible to create a class that extends the functionality of a previously defined class

◦ Known as inheritance

All classes inherit from the great mother class (directly or indirectly): java.lang.Object

It is possible to overload the methods of the super class in order to provide custom functionality

Advanced Java 25

How many methods has Animal?

A. 1

B. 2

C. 9

D. 10

E. 11

Advanced Java 26

public class Animal{

private String color;

public Animal(String c) {

color = c;

}

public String getColor() {

return color;

}

}

Collections

Motivation ◦ Why use collections?

Realisation of one-to-many relations ◦ Import, declare, initialise

The extended for-loop

Autoboxing and wrapperclasses

Other collections in Java

Advanced java 27

iTunes – a motivating example

Track

Playlist

28

iTunes class model

Advanced java

Track

String getName()

String getArtist()

int getTime()

Player

void add(PlayList p)

List<PlayList> find(String q)

void print()

* PlayList

String getName()

void addTrack(Track t)

void print()

Track shortestTrack()

Track longestTrack()

List<Track> search(String q)

List<Track> longerThan(int r)

void shuffle()

*

29

*Associations

Arbitrary many objects

of the type

Playlist

Track

Another example

An address book where you can:

◦ Add contacts (persons) – as many as you like

◦ Print out the address book

◦ Find a phonenumber given a name

◦ Find the average age of the contacts

Problem

◦ How do the address book remember the persons?

◦ How do we implement the one-to-many relation?

Advanced Java

AddressBook

void addPerson(Person p)

void print()

String getPhone(String name)

int averageAge()

Person

String getName()

String getNumber()

int getAge() ? *

30

Advanced Java

Collections – collections of objects

Object references ◦ To access an object we new an object reference(a variable)

◦ To access 10.000 objects we need 10.000 object references...

Collections ◦ A special kind of object that can store (references to)

objects

◦ E.g. ArrayList

java.util

◦ A package that (among other) contains the classes of Java’s so called collection framework

31

Advanced Java

Example: List of persons public void testMethod1() {

Person tp;

ArrayList<Person> l= new ArrayList<Person>();

tp= new Person( "Jeppe", "89425665", 33 );

l.add(tp);

tp= new Person( "Ole", "32789878", 28 );

l.add(tp);

tp= new Person( "Linda", "90023234", 21 );

l.add(tp);

}

32

Advanced Java

Objectmodel for person example l: ArrayList

0 1 2 size() = 3

name:

number:

age: 21

”Linda”

”90023234”

name:

number:

age: 33

”Jeppe”

”89425665”

name:

number:

age: 28

”Ole”

”32789878”

33

Implementation of one-to-many - UML

Advanced Java

AddressBook

ArrayList<Person> persons

void addPerson(Person p)

void print()

String getPhone(String name)

int averageAge()

Person

String getName()

String getNumber()

int getAge() *

34

Implementation of one-to-many

(code) To implement a one-to-many accociation you need to:

1. Import a collection (e.g. a list)

import java.util.ArrayList;

2. Declare an attribute of the appropriate type

private ArrayList<Person> persons;

3. Initialise the collection in the construktor

public AddressBook(){

persons = new ArrayList<Person>();

}

Advanced java 35

Advanced Java

Collection

ArrayList<E>

◦ lists (sequences) of objects of type E

public class ArrayList<E> {

boolean add(E o){}

void add(int index, E element){}

E get(int index){}

boolean contains (Object o){}

boolean isEmpty(){}

Iterator<E> iterator(){}

boolean remove(Object o){}

int size(){}

...

} See JavaDoc...

36

Advanced Java

Iteration using ”new” for-loop public void testMethod1() {

Person tp;

List<Person> l= new ArrayList<Person>();

tp= new Person( ”Jeppe”, ”89525665”, 33 ); l.add(tp);

tp= new Person( ”Ole”, ”32789878", 28 ); l.add(tp);

tp= new Person( ”Linda”, ”90023234”, 48 ); l.add(tp);

// for all persons p in l ...

for ( Person p : l ) {

System.out.println(p);

}

}

37

Advanced Java

Example: averageAge

/**

* return the average age of the people in the addressbook

*/

public int averageAge() {

?

}

Specification (WHAT)

38

Advanced Java

Implementation (1)

/**

* return the average age of

* the people in the address book

*/

public int averageAge() {

return ageSum() / persons.size();

}

Implementation (HOW)

39

/**

* return the sum of the age of the

* people in the address book

*/

private int ageSum() {

?

}

Advanced Java

Implementation (2)

/**

* return the sum of the age of the

* people in the address book

*/

private int ageSum() {

int result= 0;

// accumulate the sum of ... in variable result

return result;

}

40

Advanced Java

Implementation (3)

/**

* return the sum of the age

* of the people in the address book

*/

private int ageSum() {

int result= 0;

for (Person p : persons) {

result= result + p.getAge();

}

return result;

}

41

It’s time for live coding

Advanced Java 44

Concert

- Venue: String

- spectators: int

- rating: int

+ get...()

+ set...()

Tour

- name: String

+ get...()

+ set...()

+ getBigConcerts(int i):

ArrayList<Concert>

*

Advanced Java

Container classes in Java

HashSet impl Set

TreeSet impl SortedSet

ArrayList impl List

LinkedList impl List

HashMap impl Map

TreeMap impl SortedMap

Interfaces (specifikation)

Classes

(implementation)

W

H

A

T

H

O

W

49

Advanced Java

Different containers

List

◦ ordered collection of objects (the sequence is important)

◦ 0, 1, ..., size()-1

Set

◦ a collection of objects

◦ unordered or ordered (sorted)

Collection

◦ Super-concept for List and Set

Map

◦ Set of pars

◦ ordered or unordered (sorted)

[ 4, 5, 1, 7 ] [ 7, 5, 1, 4 ]

{ 4, 5, 1, 7 } { 7, 5, 1, 4 }

{ (”gigantisk”, ”gigantic”), (”abe”,

”monkey”) }

0 1 2 3 0 1 2 3

50

Generic code

A small example

What is the output of the first print line?

A: [”Adam”, ”Bo”, ”Cecillie”, ”Dora”, ”Erik”]

B: [”Cecillie”, Erik”, ”Adam”, ”Bo”, ”Dora”]

C: null pointer exception

D:[]

E: [”Dora”, ”Bo”, ”Adam”, ”Erik”, ”Cecillie”]

Why?

A small example

What is the output of the last print line?

A: [”Adam”, ”Bo”, ”Cecillie”, ”Dora”, ”Erik”]

B: [”Cecillie”, Erik”, ”Adam”, ”Bo”, ”Dora”]

C: null pointer exception

D:[]

E: [”Dora”, ”Bo”, ”Adam”, ”Erik”, ”Cecillie”]

Why?

Pre-programed methods The class Collections contains a number of useful methods:

In general the methods require that T defines a total ordering

int binarySearch(List<T> l, T key)

void copy(List<T> dest, List<T> src)

boolean disjoint(Collection<T> c1, Collection<T> c2)

int frequency(Collection<T> c, Object o)

T max(Collection<T> c)

T min(Collection<T> c)

void reverse(List<T> l)

void shuffle(List<T> l)

void sort(List<T> l)

...

What is a total ordering (1)?

A. An operator (e.g. ≤) where for every a and b:

a ≤ b or b ≤ a

B. A way to handle orders by a firm

C. An operator (e.g. ≤) where

a) If a ≤ b and b ≤ a then a = b

b) If a ≤ b and b ≤ c then a ≤ c

c) a ≤ b or b ≤ a

D. An operator (e.g. ≤) where

a) Both a ≤ b and b ≤ a can not be true

b) If a ≤ b and b ≤ c then a ≤ c

c) a ≤ b or b ≤ a

E. Have no idea

Advanced Java 56

Implementing a total ordering

i.e. by implementing the interface Comparable

Advanced Java 57

Shortest Track

// We assume that tracks is non-empty

public Track shortestTrack(){

Track res;

res= tracks.get(0); //res == min

element so far

for ( Track t : tracks ){

if ( t.getTime() < res.getTime() ) {

res= t;

}

}

return res;

}

Youngst Person

// We assume that persons are non-empty

public Person youngestPerson(){

Person res;

res= persons.get(0); //res == min

element so far

for ( Person p : persons ){

if ( p.getAge() < res.getAge() ) {

res= p;

}

}

return res;

}

What is the difference?

public Person youngestPerson(){

Person res= persons.get(0); //res == min element so far

for ( Person p : persons ){

if ( p.getAge() < res.getAge() ) {

res= p;

} }

return res;

}

public Track shortestTrack(){

Track res= tracks.get(0); //res == min element so far

for ( Track t : tracks ){

if ( t.getTime() < res.getTime() ) {

res= t;

} }

return res;

}

Can we generalize these two methods?

public Person youngestPerson(){

Person res= persons.get(0); //res == min element so far

for ( Person p : persons ){

if ( p.getAge() < res.getAge() ) {

res= p;

} }

return res;

}

public Track shortestTrack(){

Track res= tracks.get(0); //res == min element so far

for ( Track t : tracks ){

if ( t.getTime() < res.getTime() ) {

res= t;

} }

return res;

}

We want to be able to...

// Assumption: l is not empty

public T min(List<T> l) {

T res;

res= l.get(0); // res == min element so far

for ( T e : l ) {

if ( ”e < res” ) {

res= e;

}

}

return res;

}

...give the element type as a parameter

...comparation

parametirized

How do you compare objects?

public interface Comparable<T> {

/**

* @returns whether this object is

* smaller (negative integer)

* equal (0)

* or greater (positive integer)

* than object o

*/

public int compareTo(T o);

}

Programming using the interface Comparable

public <T> T min(List<? extends T> l) {

T res;

res= l.get(0); // res == min element so far

for ( T e : l ) {

if ( e.compareTo(res) < 0 ) {

res= e;

}

}

return res;

}

Use of interfaces (implementer-role)

Think of the interface as a role

Objects from a given class can play the

role described by the interface

◦ Track-objects can play the role Comparable

public class Track implements Comparable<Track> {

...

public int compareTo(Track o) {

...

}

}

Decoupling of program components(1)

Collections

T min(Collection<T> c)

void sort (List<T> l)

...

<<interface>>

Comparable

Person

Dice

Track

Decoupling of program components(2)

There is a need for lowering the decency

between program components

Interfaces is used to describe the minimal

knowledge between program components

By using interfaces it is possible to

develop, compile, test etc. collaborating

program components

◦ There can be a long time between the

development of the components (e.g.

Collections.sort() and your class, ...)

Division of resposibilities

min(myList)

Collections

Comparable

: Driver

e.compareTo(res)

e: T

Division of resposibilities

public T min(List<T> l) {

T res;

res= l.get(0);

// res == min element so far

for ( T e : l ) {

if ( e.compareTo(res) < 0 ) {

res= e;

}

}

return res;

}

dIntProg, E10

public class Driver {

public void run() {

ArrayList<Track> myList;

myList= new ArrayList<Track>();

...

Track t= Collections.min(myList);

}

}

Comparable

public class Track

implements Comparable<Track> {

...

public int compareTo(Track t) {

...

}

}

Interfaces in Javas Collection API

HashSet impl Set

TreeSet impl SortedSet

ArrayList impl List

LinkedList impl List

HashMap impl Map

TreeMap impl SortedMap

Interfaces (specification)

Classes (implementation)

More than one criterium Use Comparator ◦ Separate encapsulation of comparison

◦ In stead of the class that you want to compare implements Comparable a separate class is created that implements Comparator

public interface Comparator<T> {

/**

* @returns whether o1 is

* smaller (negative integer)

* equal (0)

* or greater (positive integer)

* than o2

*/

public int compare(T o1, T o2);

}

Comparable vs Comparator – p1

= comparism logic

The interface:

Comparable vs Comparator – p2

public interface Comparable<T> {

/**

* @returns whether this object is

* smaller (negative integer)

* equal (0)

* or greater (positive integer)

* than object o

*/

public int compareTo(T o);

}

public interface Comparator<T> {

/**

* @returns whether o1 is

* smaller (negative integer)

* equal (0)

* or greater (positive integer)

* than o2

*/

public int compare(T o1, T o2);

}

Comparable vs Comparator – p3

Use with the Collections class: public void printByAge(){

Collections.sort(persons);

for (Person p : persons){

System.out.println(p);

}

}

public void printByAge(){

Collections.sort(persons, new AgeComparator());

for (Person p : persons){

System.out.println(p);

}

}

Your own interfaces

Of cause it is possible to create ones own interfaces

◦ But why?

AddressBook:

What is in common/different?

◦ Can it be factored out?

public ArrayList<Person> findBelow(int a){

ArrayList<Person> result = new ArrayList<Person>();

for (Person p : persons){

int age = p.getAge();

if (age < a) {

result.add(p);

}

}

return result;

}

public ArrayList<Person> findAll(String q){

ArrayList<Person> result = new ArrayList<Person>();

for (Person p : persons){

String name = p.getName();

if (name.contains(q)) {

result.add(p);

}

}

return result;

}

Own interfaces

Can filter out objects

Can be used for:

◦ AddressBook

findAll, findBelow, findPerson, getPhone?

Or more general:

Can be used for

◦ Player

nameSearch, artistSearch, longerThan, shorterThan,

shortestTrack?

Filter

public interface PersonFilter{

public boolean test(Person o);

}

public interface Filter<T>{

public boolean test(T o);

}

Abstract og concrete type

Abstract and concrete type

Abstract type (ADT)

Concrete type(s) (CDT)

Super- and subtypes

An abstract type is supertype to its

concrete type(s)

A concrete type is subtype to its abstract

supertype(s)

Type-rule for assignment

The type of the expression on the right

hand side must be a subtype of the

variable on the left hand side:

v = exp;

T(v) ≥ T(Exp)

A type is its own subtype ()

How many legal assignments?

A. 0

B. 1

C. 2

D. 3

E. Do not know

Advanced Java 83

Comparator c;

c= new AgeComparator();

c= new Person();

How many legal assignments (2-1)?

A. 0

B. 1

C. 2

D. 3

E. Do not know

Advanced Java 84

List<Person> l;

l= new ArrayList<Person>();

l= new HashSet<Person>();

How many legal assignments (3-2)?

A. 0

B. 1

C. 2

D. 3

E. Do not know

Advanced Java 85

List<Person> l;

l= new ArrayList<Person>();

l= new LinkedList<Person>();

Interface vs. Class

An interface describes an abstract type

◦ Can be used as the type for variables and return type

of methods

A class describes a concrete type

◦ Can be used like interfaces AND for the instantiation

of objects

List<Person> l;

public List<Person> next(List<Person> l)

l = new ArrayList<Person>();

public ArrayList<Person> sort(ArrayList<Person> l)