advanced java - bennedsen.orgbennedsen.org/java/repetition-slides.pdf · advanced java 8. student...
TRANSCRIPT
Advanced Java
Dr. Jens Bennedsen,Aarhus University, School of EngineeringAarhus, [email protected]
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
Slides etc
Slides etc avaliable at: www.bennedsen.org/java
Advanced Java 3
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
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
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
Advanced Java 7
Review and comment
Advanced Java 8
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
Mentimeter quiz
Log on and answer the following:
”What is a class in Java?”
Advanced Java 10
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
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
Java SE
Advanced Java 14
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
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 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());
}
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());
}
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 24
Exception: Constants arerepresented by variables. Theyare 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 25
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 {…
}
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
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
Javadoc source code
Advanced Java 29
Generated javadoc
Advanced Java 30
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
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;}
}
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
iTunes – a motivating example
Track
Playlist
34
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
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
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
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
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
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
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
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
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
Advanced Java
Example: averageAge
/*** return the average age of the people in the addressbook*/
public int averageAge() {
?
}
Specification (WHAT)
44
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() {?
}
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
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
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>
*
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
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
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 exceptionD:[]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 exceptionD:[]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 ≤ 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
Implementing a total ordering i.e. by implementing the interface Comparable
Advanced Java 63
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;
}
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;
}
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;
}
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
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
PersonDice 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 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) {
...}
}
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. 0B. 1C. 2D. 3E. Do not know
Advanced Java 89
Comparator c;c= new AgeComparator(); c= new Person();
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>();
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>();
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)