Oop Java
Oop Java
Oop Java
Java
1. Java Language
2. Object-Oriented Programming
3. Inheritance and Polymorphism
4. Static Members
5. Interfaces and Abstract Classes
6. Exceptions and Nested Classes
7. Threads
8. GUI Programming
9. Collections and Generics
©2016 Margit ANTAL
Module 1
Java language
● History
● Java technology: JDK, JRE, JVM
● Properties
● 'Hello world' application
● Garbage Collection
JVM
● Object-oriented
● Interpreted
● Portable
● Secure and robust
● Scalable
● Multi-threaded
● Dynamic language
● Distributed
©2016 Margit ANTAL
Hello World Application
1. Write the source code: HelloWorld.java
HelloWorld.class
java HelloWorld
Runtime
JVM
● Class
– Attributes and methods
● Object (instance)
● Information hiding
● Encapsulation
● Constructors
● Packages
©2016 Margit ANTAL
Class
● Is a user-defined type
–
–
Describes the data (attributes)
Defines the behavior (methods) } members
<attribute_declaration>*
<constructor_declaration>*
<method_declaration>*
● Examples
<statement>*
/* C language */
struct Date { Date d;
int year, month, day; d.day = 32; //invalid day
};
d.month = 2; d.day = 30;
// invalid data
d.day = d.day + 1;
// no check
// Java language
public class Date { Date d = new Date();
private int year, month, day; //no assignment
public void setDay(int d){..} d.setDay(32);
public void setMonth(int m){..} // month is set
public void setYear(int y){..} d.setMonth(2);
public int getDay(){...} // no assignment
public int getMonth(){...} d.day = 30;
public int getYear(){...}
}
public Date( ){
}
}
String
Thread Button
● Examples:
package java.lang; - statement at the beginning of the
source file
- only one package declaration per
public class String{ source file
- if no package name is declared →
… the class is placed into the default
} package
● Primitive types
● Reference Type
● Parameter Passing
● The this reference
● Variables and Scope
● Casting
– Primitive (8)
● Logical: boolean
● Textual: char
● Integral: byte, short, int, long
● Floating: double, float
– Reference
● All others
– Characteristics:
● Literals:
– true
– false
● Examples:
– boolean cont = true;
– boolean exists = false;
– Characteristics:
● Represents a 16-bit Unicode character
● Literals are enclosed in single quotes (' ')
● Examples:
– 'a' - the letter a
– '\t' - the TAB character
– '\u0041' - a specific Unicode character ('A') represented by
4 hexadecimal digits
– Characteristics:
● Use three forms:
– Decimal: 67
– Octal: 0103 (1x8^2+0x8^1+3x8^0)
– Hexadecimal: 0x43
● Default type of literal is int.
● Literals with the L or l suffix are of type long.
– Ranges:
Type Length Range
byte 1 byte -27..27-1
short 2 byte -215..215-1
int 4 byte -231..231-1
long 8 byte -263..263-1
– Characteristics:
● Size:
– float – 4 byte
– double – 8 byte
● Decimal point
– 9.65 (double, default type)
– 9.65f or 9.65F (float)
– 9.65D or 9.65d (double)
● Exponential notation
– 3.41E20 (double)
object day 0
month 0
year 0
The address
of the object
reference date1 ???
object day 20
month 6 0x01a2345
year 2000
The reference
points to
the object
reference date1 0x01a2345
0x01a2345
object day 20
month 6
year 2000
0x01a2345 day 20
object month 6
year 2000
pt.changeObjectDay( oneDate, 12 );
System.out.println( oneDate.getDay() );
Output:
100
2016
12
Usage:
– To resolve ambiguity between instance variables and
parameters
– To pass the current object as a parameter to another
method
● Logical operators
● Bitwise operators ( ~, ^, &, |, >>, >>>, < )
● String concatenation ( + )
● String
– Immutable – once created can not be changed
– Objects are stored in the Constant String Pool
● StringBuffer
– Mutable – one can change the value of the object
– Thread-safe
● StringBuilder
– The same as StringBuffer
– Not thread-safe
● Declaring arrays
● Creating arrays
● Arrays of primitive and reference type
● Initialization of elements
● Multidimensional arrays
● What is an array?
– Group of data objects of the same type
● Arrays of primitive types:
int t[];
int [] t;
Point[] p;
//array creation
t = new int[10];
//array creation
t = new int[10];
//array declaration
Point [] t;
//array declaration
Point [] p;
● Rectangular arrays:
int [][] array = new int[3][4];
● Non-rectangular arrays:
int [][] array;
array = new int[2][];
array[0] = new int[3];
array[1] = new int[5];
– Strong – Composition
Passenger
– Weak – Aggregation Car
Person Brain
Car Passenger
Association
Aggregation
Composition
Person Date
//...
}
//...
}
//...
}
● Inheritance
– Parent class
– Subclass, Child class
● Polymorhism
– Overriding methods
– Overloading methods
– The instanceof operator
– Heterogenous collections
● Opportunities:
(1) add new data → department
(2) add new methods → e.g. getDepartment()
(3) override inherited methods → toString()
private Yes
default Yes Yes
protected Yes Yes Yes
public Yes Yes Yes Yes
//...
Employee e1 = new Employee(“Endre”,2000,new Date(20,8, 1986));
Manager m1 = new Manager(“Johann”,3000,
new Date(15, 9, 1990),”Sales”);
//...
System.out.println( createMessage( e1 ) );
System.out.println( createMessage( m1 ) );
Liskov Substitution!
// print employees
for( Employee e: emps ){
System.out.println( e.toString() );
}
// count managers
int counter = 0;
for( Employee e: emps ){
if( e instanceof Manager ){
++counter;
}
}
//Solution
System.out.println( ((Manager) e).getDepartment() );// CORRECT
//Better Solution
if( e instanceof Manager ){
System.out.println( ((Manager) e).getDepartment() );
}
Animal
//expressions
a instanceof Animal → true
Mammal
a instanceof Mammal → true
a instanceof Bear → true
a instanceof Date → false
Bear
● Inheritance
– Subclass opportunities
● Polymorphism
– Overriding methods
– Overloading methods
– Polymorphic argument
– Heterogenous collections
– Static vs. dynamic type
– The instanceof operator
©2016 Margit ANTAL
Inheritance and Polymorphism
Methods Common to All Objects
Output?
Output?
●
Reflexive
– x.equals(x):true
●
Symmetric
– x.equals(y):true ↔ y.equals(x):true
● Transitive
– x.equals(y):true and y.equals(z):true →
x.equals(z):true
● Characteristics:
– Converts an object to a String
– Override this method to provide information
about a user-defined object in readable
format
int i = 420;
Integer anInt = new Integer(i); // boxing
int j = anInt.intValue(); // unboxing
Too slow!!!
p1 :Product
sNumber:1
Class Product
counter: 2
p2 :Product
sNumber:2
public Product() {
counter++;
sNumber = counter;
}
}
public Product() {
counter++;
sNumber = counter;
}
System.out.println(Product.getCounter());
} Product p = new Product();
System.out.println(Product.getCounter());
Output?
Recommended:
<class name>.<member_name>
System.out.println(Product.getCounter());
Product p = new Product();
System.out.println(p.getCounter());
Output?
public InstanceCounter(){
++counter;
}
System.out.println( InstanceCounter.getCounter());
System.out.println( InstanceCounter.getCounter());
private Singleton(){
}
static {
// e.g. read counter from a file
}
}
● Class
– You cannot subclass a final class.
● Method
– You cannot override a final method.
● Variable
– A final variable is a constant.
– You can set a final variable only once.
– Assignment can occur independently of the
declaration (blank final variable).
©2016 Margit ANTAL
Blank Final Variables
public Employee(){
ID = createID();
}
● Properties
– Define types
– Declare a set of methods (no implementation!) –
ADT – Abstract Data Type
– Will be implemented by classes
class interfaces
«i nte rface»
Driveable
+ sta rt() : voi d
+ forw a rd() : voi d
+ turn (d ou b le ) : vo id
+ sto p() : voi d
@Override
public void forward() {
System.out.println("The bicycle moves forward");
}
@Override
public void turn( double angle) {
System.out.println("The bicycle turns "+angle+
" clockwise");
}
@Override
public void stop() {
System.out.println("The bicycle has been stopped");
}
}
«interface»
Driveable
+ start() : void
+ forw ard() : void
+ turn(double) : void
+ stop() : void
Bicycle Car
a) Driveable a;
b) Driveable a = new Driveable();
c) Driveable t[] = new Driveable[ 3 ];
d) public void drive( Driveable d );
● Interface: « i n te rfa ce »
Driveable
– User-defined type + sta rt() : vo i d
+ fo rw a rd () : vo i d
– Set of methods +
+
tu rn (d o u b le ) : vo id
sto p () : vo i d
– No implementations provided
– Cannot be instantiated
● Class: Bicycle
+ sta rt() : vo i d
– User-defined type +
+
fo rwa rd () : vo i d
tu rn (d o u b le ) : vo id
+ sto p () : vo i d
– Set of data and methods + to S trin g () : S tri n g
}
} ArrayList<T> LinkedList<T>
}
class class8_1
Shape
# a re a : d o u b l e
+ d ra w () : vo i d
Circle Square
- ra d i u s: d o u b l e - si ze : d o u b l e
+ Sq u a re (d o u b l e )
+ Ci rcle (do u b l e )
+ d ra w() : vo i d
+ d ra w() : vo i d
@Override
public void draw() {
System.out.println("I am a square");
}
(no implementation)
– Cannot be instantiated
– Designed to be subclassed
Square
● Class: - si ze : d o u b l e
+ S q u a re (d o u b l e )
– User-defined type + d ra w() : vo i d
● https://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/
interface Comparable {
int compareTo(Object o);
}
x.compareTo(y):
0: x equal to y
positive: x > y;
negative: x< y;
interface Comparable<T> {
int compareTo(T o);
}
Attempts to use a
different type are caught
at compile time!!!
{ ...
Comp arable
@Override Point
a.equals(b)
exactly when
a.compareTo(b) == 0
©2016 Margit ANTAL
The Comparator<T> interface
– For each class we can define only one natural ordering through the
Comparable interface
– We can define an unlimited number of ordering using the
Comparator interface
interface Comparator<T> {
int compare (T x, T y);
}
@Override
public int compare(Point p1, Point p2) {
Double d1 = p1.distanceTo(o);
Double d2 = p2.distanceTo(o);
return d1.compareTo(d2);
}
}
● Define exceptions
● Exception handling: try, catch, and
finally
● Exception categories
● User-defined exceptions
● Enumerations
● Nested classes
java AddArguments 1 2 3
Sum: 6
try{
// critical code block
// code that might throw exceptions
} catch( MyException1 e1 ){
// code to execute if a MyException1 is thrown
} catch( MyException2 e2 ){
// code to execute if a MyException1 is thrown
} catch ( Exception e3 ){
// code to execute if any other exception is thrown
}
try{
connectDB();
doTheWork();
} catch( AnyException e ){
logProblem( e );
} finally {
disconnectDB();
}
● The code in the finally block is always executed (even in case of return
statement)
Usage:
ClassName.countLines(“input.txt”);
Usage:
try{
ClassName.countLines(“input.txt”);
} catch( FileNotFoundException e ){
e.printStackTrace();
}
Principles
● You do not need to declare runtime (unchecked)
exceptions
● You can choose to handle runtime exceptions (e.g.
IndexArrayOutOfBounds, NullPointerException)
Output
UP, fel, 0
RIGHT, jobb, 1
DOWN, le, 2
LEFT, bal, 3
● When?
– If a class is used only inside of another class
(encapsulation)
– Helper classes
Iterator it = list.createIterator();
while( it.hasnext() ){ Factory Method
System.out.println( it.next() ); Design Pattern
}
● Definition
● Creation: Thread and Runnable
● Synchronization
● Executors and thread pools
What are threads?
● Operating Systems
- lightweight process
- runs in the address space of a process
- has its own program counter (PC)+stack
- shares code and data with other threads
● Object-oriented Programming
- an object – an instance of the class Thread
Threads
●
java.lang.Thread = Infrastructure(PC+Stack)
●
java.lang.Runnable = Code
Thread's creation (1)
public class MyRunnable implements Runnable{
private int id;
public MyRunnable(int id ){
this.id = id;
}
} « i n te rface»
} +
Runnable
ru n() : voi d
… « rea l i ze »
MyRunnable r = new MyRunnable(1);
Thread t = new Thread( r ); Thread
MyRunnable
Cl a ss2
+ run () : voi d
Starting the thread
t.start();
Calls the thread object's run method
Thread's creation (1)
Output?
Thread's creation (2)
class MyThread extends Thread {
private int id;
…
Thread t = new MyThread(1);
t.start();
Thread's creation (2)
t1.start(); « i n te rfa ce »
t2.start(); +
Runnable
ru n () : vo i d
}
}`
Thread
+ ru n () : vo i d
MyThread
+ ru n () : vo i d
Example (1)
Output?
Example (2)
public class MyFirstRunnable implements Runnable{
@Override
public void run() {
System.out.println("In a thread");
}
}
Usage:
Runnable runnable = new MyFirstRunnable();
for(int i = 0; i<25; i++){
new Thread(runnable).start();
}
Output?
Operations on threads
try {
Thread.sleep(1000);
} catch (InterruptedException e){
e.printStackTrace();
}
sleep()
try {
Thread.sleep(1000);
} catch (InterruptedException e){
e.printStackTrace();
}
join()
Thread2
Need for synchronization
class Counter {
private int value;
value++
1. Read the current value of "value"
2. Add one to the current value
3. Write that new value to "value"
Solution (1)
entered
● if the lock is not available, thread enters a
waiting queue
● if the lock is returned, thread is resumed
Thread Safe
● Long
● Double
Executors and thread pools
http://www.vogella.com/tutorials/JavaConcurrency/article.html#threadpools
ExecutorService
Callable
Future
Module 8
GUI Programming
Swing
JMenuItem
JButton
JLabel
JPanel
JFrame
contains a picture
JFrame
– Top level container
● can have menu bars Menu Bar
– Contains a JRootPane Frame
– Have BorderLayout as
the default layout manager
● FlowLayout
● BorderLayout
● GridLayout
● GridBagLayout
● Aggregation
– FrameAggregation
● Inheritance
– FrameInheritance
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(100, 100, 200, 200);
frame.setVisible(true);
}
frame.setJMenuBar(createMenu());
http://docs.oracle.com/javase/tutorial/uiswing/components/border.html
● Event handler – a
method that Event Handler
● receives an event object, actionPerformed( ActionEvent e){
...
● deciphers it, }
● and processes the user's
interaction
Event Handler1
actionPerformed( ActionEvent e){
...
}
Event Handler2
actionPerformed( ActionEvent e){
...
}
● GUI components trigger the handlers for the type of event that
has occurred
Event handler
public DrawComponent(){
this.addMouseListener(new MouseAdapter(){
@Override
public void mousePressed(MouseEvent e) {
points.clear();
points.add( new Point( e.getX(), e.getY()));
}
});
this.addMouseMotionListener(new MouseMotionAdapter(){
@Override
public void mouseDragged(MouseEvent e) {
points.add( new Point( e.getX(), e.getY()));
DrawComponent.this.repaint();
}
});
}
…
}
● General listeners
– ComponentListener
– FocusListener
– MouseListener
● Special listeners
– WindowListener
– ActionListener
– ItemListener
`
● Problem:
– Sometimes you need only one event handler method, but
the listener interface contains several ones
– You have to implement all methods, most of them with
empty ones
● Solution:
– An Event Adapter is a convenience class
– Implements all methods of a listener interface with empty
methods
– You extend the adapter class and override that specific
method
©2016 Margit ANTAL
Event Adapter Classes
Example
● Data Structures
● Interfaces: Collection, List, Set, Map, ...
● Traversing collections
● Overriding equals and hashCode
● Sorting
● Problems
● What is?
– Unified architecture
● Interfaces – implementation-independence
● Implementations – resusable data structures
● Algorithms – reusable functionality
– Best-known examples
● C++ Standard Template Library (STL)
● Smalltalk collections
● Benefits:
– Reduces programming effort
– Increases performance
● High performance implementations of data structures
– Fosters software reuse
« i n te rfa ce » « i n te rfa ce »
Collection Map
« i n te rfa ce »
SortedSet
class interfaces
« i n te rfa ce »
Collection
Methods:
● add(T what): boolean
● remove(T what): boolean
« i n te rfa ce » « i n te rfa ce » ● size(): int
Set List
● contains(T what): boolean
● containsAll(Collection c):
boolean
● equals(T what): boolean
« i n te rfa ce »
SortedSet ● iterator(): Iterator
«interface»
Collection
« interface» «interface»
Set List
ArrayList 0 1 2 3 4
size capacity
LinkedList
Source
TreeSet
Source
HashSet
Source
● Ordered
– You can iterate through the collection in a specific (not random) order.
– Each element has a previous and a next element (except the first and
the last ones).
● Sorted
– The order is determined according to some rule or rules (sort order).
– Is a specific type of ordering
● Collections
– HashSet: unordered and unsorted
– List: ordered but unsorted
– TreeSet: ordered and sorted
©2016 Margit ANTAL
Complexities
while(it1.hasNext()){
System.out.println(it1.next());
}
--------------------------------------------
ArrayList<Person> list2 = new ArrayList<>();
…
Iterator<Person> it2 = list2.iterator();
while(it2.hasNext()){
System.out.println(it2.next());
}
Problem:
Split a text file into words and print the words in
(1) Increasing order (alphabetically)
(2) Decreasing order
Problem:
Split a text file into words and print the distinct words in
(1) Increasing order (alphabetically)
(2) Decreasing order
Solutions:
(1)TreeSet<String>
(2)TreeSet<String> (Comparator<String>)
Problem:
Generate 2D Points having integer coordinates and
print them in increasing order. Points are ordered
according to their distance to the origin.
@Override
public int compareTo(Point o) {
double d = this.distanceTo(origin)-o.distanceTo(origin);
if( d < 0 ) return -1;
else
if( d>0 ) return 1;
else return 0;
}
}
@Override
public int compareTo(Point o) {
double d = this.distanceTo(origin)-o.distanceTo(origin);
if( d < 0 ) return -1;
else
if( d>0 ) return 1;
else return 0;
}
}
Requirements:
● Optimal solution is required.
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Point other = (Point) obj; HashSet
if (this.x != other.x) { ● Finding an element: O(1)
return false;
}
if (this.y != other.y) { Implementation
return false; Random number generator: seed = 0
} N = 1.000.000
return true; M = 10.000
} Duplicates: 4976
Time: approx. 1 s
Problem
2. solution - HashSet
@Override
@Override
public int hashCode() {
public
intinthash
hashCode() {
= (x *31)^ y;
int hash =hash;
return (x ^ y) ;
} return hash; ●
}
@Override
@Override
public boolean equals(Object obj) {
public
if boolean
(obj == equals(Object
null) { obj) {
if (obj == null)
return {
false;
} return false;
}if (getClass() != obj.getClass()) {
if (getClass() != obj.getClass())
return false; {
} return false;
}final Point other = (Point) obj;
HashSet
final Point other!=
if (this.x = (Point) obj; {
other.x)
if (this.x != other.x)
● Finding an element: O(1)
return{ false;
} return false;
}if (this.y != other.y) { Implementation
if (this.y != other.y)
return{ false; Random number generator: seed = 0
} return false;
What happens if N = 1.000.000
}return true; we don't override M = 10.000
} return true; equals? Duplicates: 4976
}
How many duplicates? Time: approx. 1s
Problem
2. solution - HashSet
@Override
public int hashCode() {
int hash = 1;
return hash;
} ●
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Point other = (Point) obj;
if (this.x != other.x) {
What
return happens?
false;
}
if (this.y != other.y) {
return false;
}
return true;
}
Problem
2. solution - HashSet
Examples:
Key: country, Value: capital city
● Slovenia → Ljubljana
● Austria → Vienna
● Hungary → Budapest
● Romania → Bucharest
«in te rface »
Map HashMap: unordered, no duplicates
HashMap TreeMap
//...
TreeMap<String, MyLong> frequency = new TreeMap<>();