advanced java - bennedsen.orgbennedsen.org/java/repetition-slides.pdf · advanced java 8. student...

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

Upload: others

Post on 24-Jun-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

Advanced Java

Dr. Jens Bennedsen,Aarhus University, School of EngineeringAarhus, [email protected]

Page 2: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

Syllabus Monday: Java overview◦ Classes/Objects, Interfaces, Collections, Javadoc, …

Tuesday: Graphical User Interfaces (AWT/Swing) ◦ Design patterns, Swing compenents, Events

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

Page 3: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

Slides etc

Slides etc avaliable at: www.bennedsen.org/java

Advanced Java 3

Page 4: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

Mandatory assignments Three mandatory assignments:◦ Repetition: Monday February 18th12.00

CET + February 25th 12.00.◦ GUI + Databases: Thusday February 28th

12.00 CET + March 7th 12.00◦ Threads: Monday March 11th 12.00 CET +

March 18th 12.00

Advanced Java 4

Page 5: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

Rules for the hand-ins◦ The hand in MUST be ONE zip-file/pdf-file lastname-firstname.zip/pdf OR lastname1-

firstname1-AND-lastname2-firstname2.zip/pdf

◦ You must hand-in individually or in pais◦ Plagiarism check. ZERO points for all the

students. ◦ Two step process: 1) Hand-in, 2) review◦ Grading: 75% + 25% Hand-in: The quality of code/explanations Review: The quality of comments etc.

Advanced Java 5

Page 6: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

Hand-in

We will be using peergrade.io You mst join my class: https://app.peergrade.io/join Using code: AJJ452 Help: http://help.peergrade.io/how-to-

s/how-to-for-students/how-to-join-with-a-code

Advanced Java 6

Page 7: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

Advanced Java 7

Page 8: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

Review and comment

Advanced Java 8

Page 9: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

Student response system

We will be using Mentimeter: Go to menti.com (or download it from

Google play/appstore) First a warm-up quiz

Advanced Java 9

Page 10: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

Mentimeter quiz

Log on and answer the following:

”What is a class in Java?”

Advanced Java 10

Page 11: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

TPS

Some slides have the icon: ◦ 1) YOU think QUETLY

about the question (X sec)◦ 2) YOU turn to your

neighbor and discuss your answers. Come to an agreement on one answer (Y sec)◦ 3) All pairs ”vote” (30 sec)

Advanced Java 11

Page 12: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

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 leaks12Advanced Java

Page 13: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

Java SE

Advanced Java 14

Page 14: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

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 15

Page 15: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

Advanced Java

Class

State Behaviour Attribute Type Constructor Signature Method Return type Parameter Argument Accessor Mutator Assignment

Page 16: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

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

Page 17: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

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

Page 18: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

How many Person objecs arecreated (1)?

A. 1B. 2C. 3D. 4E. 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());

}

Page 19: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

What is the output of the program (1)?

A. 0B. 23C. 24D. 42E. 66

Advanced Java 22

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

}

Page 20: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

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

}

Page 21: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

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 24

Exception: Constants arerepresented by variables. Theyare written with all UPPERCASE LETTERS and words seperated by underscore, e.g. MY_CONST

Page 22: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

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 25

Page 23: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

Packages

If you want to use the functionality, youneed 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 26

import java.util.Map;import java.awt.*;

public class Test {…

}

Page 24: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

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 27

Page 25: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

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 28

Page 26: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

Javadoc source code

Advanced Java 29

Page 27: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

Generated javadoc

Advanced Java 30

Page 28: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

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 31

Page 29: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

How many methods has Animal?

A. 1B. 2C. 9D. 10E. 11

Advanced Java 32

public class Animal{private String color;public Animal(String c) {

color = c;}public String getColor() {

return color;}

}

Page 30: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

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 33

Page 31: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

iTunes – a motivating example

Track

Playlist

34

Page 32: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

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

*

35

*−Associations

Arbitrary many objectsof the type

Playlist

Track

Page 33: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

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

36

Page 34: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

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

37

Page 35: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

Advanced Java

Example: List of personspublic 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);

}

38

Page 36: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

Advanced Java

Objectmodel for person examplel: ArrayList

0 1 2 size() = 3

name:number:age: 21

”Linda”

”90023234”

name:number:age: 33

”Jeppe”

”89425665”

name:number:age: 28

”Ole”

”32789878”

39

Page 37: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

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

40

Page 38: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

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 41

Page 39: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

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

42

Page 40: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

Advanced Java

Iteration using ”new” for-looppublic 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);}

}

43

Page 41: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

Advanced Java

Example: averageAge

/*** return the average age of the people in the addressbook*/

public int averageAge() {

?

}

Specification (WHAT)

44

Page 42: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

Advanced Java

Implementation (1)

/*** return the average age of * the people in the address book*/

public int averageAge() {return ageSum() / persons.size();

}

Implementation (HOW)

45

/*** return the sum of the age of the * people in the address book*/

private int ageSum() {?

}

Page 43: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

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;}

46

Page 44: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

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;}

47

Page 45: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

It’s time for live coding

Advanced Java 50

Concert- Venue: String- spectators: int- rating: int+ get...()+ set...()

Tour- name: String+ get...()+ set...()+ getBigConcerts(int i):

ArrayList<Concert>

*

Page 46: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

Advanced Java

Container classes in Java

HashSetimpl Set

TreeSetimpl SortedSet

ArrayListimpl List

LinkedListimpl List

HashMapimpl Map

TreeMapimpl SortedMap

Interfaces (specifikation)

Classes(implementation)

WHAT

HOW

55

Page 47: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

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

56

Page 48: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

Generic code

Page 49: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

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 exceptionD:[]E: [”Dora”, ”Bo”, ”Adam”, ”Erik”, ”Cecillie”]

Why?

Page 50: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

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 exceptionD:[]E: [”Dora”, ”Bo”, ”Adam”, ”Erik”, ”Cecillie”]

Why?

Page 51: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

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

Page 52: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

What is a total ordering (1)?A. An operator (e.g. ≤) where for every a and b:

a ≤ b or b ≤ aB. A way to handle orders by a firmC. An operator (e.g. ≤) where

a) If a ≤ b and b ≤ a then a = bb) If a ≤ b and b ≤ c then a ≤ cc) a ≤ b or b ≤ a

D. An operator (e.g. ≤) wherea) Both a ≤ b and b ≤ a can not be trueb) If a ≤ b and b ≤ c then a ≤ cc) a ≤ b or b ≤ a

E. Have no ideaAdvanced Java 62

Page 53: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

Implementing a total ordering i.e. by implementing the interface Comparable

Advanced Java 63

Page 54: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

Shortest Track

// We assume that tracks is non-emptypublic Track shortestTrack(){Track res;res= tracks.get(0); //res == min element so farfor ( Track t : tracks ){

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

}}return res;

}

Page 55: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

Youngst Person

// We assume that persons are non-emptypublic Person youngestPerson(){

Person res;res= persons.get(0); //res == min element so farfor ( Person p : persons ){

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

}}return res;

}

Page 56: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

Can we generalize these two methods?

public Person youngestPerson(){Person res= persons.get(0); //res == min element so farfor ( Person p : persons ){

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

} }return res;

}

public Track shortestTrack(){Track res= tracks.get(0); //res == min element so farfor ( Track t : tracks ){

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

} }return res;

}

Page 57: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

We want to be able to...

// Assumption: l is not emptypublic T min(List<T> l) {

T res;res= l.get(0); // res == min element so farfor ( T e : l ) {

if ( ”e < res” ) {res= e;

}}return res;

}

...give the element type as a parameter

...comparationparametirized

Page 58: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

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

}

Page 59: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

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;

}

Page 60: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

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

}}

Page 61: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

Decoupling of program components(1)

Collections

T min(Collection<T> c)void sort (List<T> l)...

<<interface>>

Comparable

PersonDice Track

Page 62: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

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

Page 63: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

Division of resposibilities

min(myList)

Collections

Comparable

: Driver

e.compareTo(res)

e: T

Page 64: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

Division of resposibilities

public T min(List<T> l) {T res;res= l.get(0);// res == min element so farfor ( 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 Trackimplements Comparable<Track> {...public int compareTo(Track t) {

...}

}

Page 65: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

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

}

Page 66: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

Comparable vs Comparator – p1

= comparism logic

Page 67: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

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

}

Page 68: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

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);}

}

Page 69: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

Your own interfaces

Page 70: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

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

Page 71: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

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

}

Page 72: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

Abstract og concrete type

Page 73: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

Abstract and concrete type

Abstract type (ADT)

Concrete type(s) (CDT)

Page 74: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

Super- and subtypes

An abstract type is supertype to its concrete type(s)

A concrete type is subtype to its abstract supertype(s)

Page 75: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

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

Page 76: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

How many legal assignments?

A. 0B. 1C. 2D. 3E. Do not know

Advanced Java 89

Comparator c;c= new AgeComparator(); c= new Person();

Page 77: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

How many legal assignments (2-1)?

A. 0B. 1C. 2D. 3E. Do not know

Advanced Java 90

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

Page 78: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

How many legal assignments (3-2)?

A. 0B. 1C. 2D. 3E. Do not know

Advanced Java 91

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

Page 79: Advanced Java - Bennedsen.orgbennedsen.org/java/repetition-slides.pdf · Advanced Java 8. Student response system Wewill be using Mentimeter: Go to menti.com (or download it from

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)