0% found this document useful (0 votes)
86 views

Java Inheritance Polymorphism

The document provides an introduction to frameworks and callbacks in Java. It discusses how frameworks use an event-driven programming model where application code registers callbacks for specific events. When an event occurs, the framework calls back the application code to perform processing before returning control back to the framework. Frameworks exhibit inversion of control via callbacks and provide integrated domain-specific functionality and structure. They also provide a semi-complete application by allowing application code to plug into the framework via hook methods. Common frameworks discussed include Android's activity framework and Java threads.

Uploaded by

ahelmy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
86 views

Java Inheritance Polymorphism

The document provides an introduction to frameworks and callbacks in Java. It discusses how frameworks use an event-driven programming model where application code registers callbacks for specific events. When an event occurs, the framework calls back the application code to perform processing before returning control back to the framework. Frameworks exhibit inversion of control via callbacks and provide integrated domain-specific functionality and structure. They also provide a semi-complete application by allowing application code to plug into the framework via hook methods. Common frameworks discussed include Android's activity framework and Java threads.

Uploaded by

ahelmy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

Introduction to Java

Frameworks & Callbacks


Douglas C. Schmidt

[email protected]
www.dre.vanderbilt.edu/~schmidt
Institute for Software
Integrated Systems
Vanderbilt University
Nashville, Tennessee, USA

Learning Objectives in this Lesson

Understand the key object-oriented


& generic programming features in
Java pertaining to frameworks &
callbacks

We cover many examples from the Java


2 class libraries & collections framework

Java Frameworks
& Callbacks
3

Frameworks & Callbacks

A framework is an integrated set


of components that provide a
reusable architecture for a
family of related applications

See www.dre.vanderbilt.edu/~schmidt/frameworks.html
4

Frameworks & Callbacks

Frameworks use an event-driven


programming model to plug
application code into them

Application
Code

Framework
Code
Register
for event
Event
occurs
Event
occurs

See en.wikipedia.org/wiki/Event-driven_programming
5

Frameworks & Callbacks

Application registers callbacks for


specific types of events that can
occur within the framework

Application
Code

Framework
Code
Register
for event
Event
occurs
Event
occurs

Frameworks & Callbacks

Application registers callbacks for


specific types of events that can
occur within the framework
e.g., arrival of network
messages, clicks on GUI
elements, etc.

Application
Code

Framework
Code
Register
for event
Event
occurs
Event
occurs

Frameworks & Callbacks

Framework calls back to application


code when an event occurs

Application
Code

Framework
Code
Register
for event
Event
occurs
Event
occurs

Frameworks & Callbacks

Framework calls back to application


code when an event occurs
The application performs its
processing in the context of
framework thread(s)

Application
Code

Framework
Code
Register
for event
Event
occurs
Event
occurs

Frameworks & Callbacks

When application callback is done


control returns to the framework

Application
Code

Framework
Code
Register
for event
Event
occurs
Event
occurs

10

Frameworks & Callbacks

When application callback is done


control returns to the framework
Lather, rinse, repeat until
application is done

Application
Code

Framework
Code
Register
for event
Event
occurs
Event
occurs

11

Frameworks & Callbacks

Frameworks have 3 characteristics

12

Frameworks & Callbacks

Frameworks have 3 characteristics


Exhibit inversion of control
via callbacks

See www.dre.vanderbilt.edu/~schmidt/Coursera/articles/hollywood-principle.txt
13

Frameworks & Callbacks

Frameworks have 3 characteristics


Exhibit inversion of control
via callbacks
i.e., it controls the main
thread of execution &
decides when application
code should run

14

Frameworks & Callbacks

Frameworks have 3 characteristics


Exhibit inversion of control
via callbacks
i.e., it controls the main
thread of execution &
decides when application
code should run

15

Frameworks & Callbacks

Frameworks have 3 characteristics


Exhibit inversion of control
via callbacks
i.e., it controls the main
execution thread & decides
when to run application code

16

Frameworks & Callbacks

Application-specific
functionality

Frameworks have 3 characteristics


Exhibit inversion of control
via callbacks
Integrated domain-specific
structure & functionality

Domain-specific functionality
for Android programs

17

Frameworks & Callbacks

Frameworks have 3 characteristics


Exhibit inversion of control
via callbacks
Integrated domain-specific
structure & functionality

Application-specific
functionality

e.g., provide default


capabilities useful to
some domain(s)

Domain-specific functionality
for Android programs

Androids frameworks focus on domains


18associated with mobile apps & services

Frameworks & Callbacks

Application-specific
functionality

Frameworks have 3 characteristics


Exhibit inversion of control
via callbacks
Integrated domain-specific
structure & functionality

Provide a semi-complete
application

Domain-specific functionality
for Android programs

19

Hook
method

Frameworks & Callbacks

Frameworks have 3 characteristics


Exhibit inversion of control
via callbacks
Integrated domain-specific
structure & functionality

Application-specific
functionality

Hook
method

Provide a semi-complete
application
Hook methods plug app
logic into the framework

Domain-specific functionality
for Android programs

Hook methods customize framework components


to run application-specific logic
20

Frameworks & Callbacks

Frameworks have 3 characteristics


Exhibit inversion of control
via callbacks
Integrated domain-specific
structure & functionality

Provide a semi-complete
application
Hook methods plug app
logic into the framework
Mediate interactions among
common abstract & variant
concrete classes/interfaces

Application-specific
functionality

Hook
method

Domain-specific functionality
for Android programs

Runnable is an abstract interface that21


provides the basis for concrete variants

Frameworks & Callbacks

Android & Java provide many


frameworks

22

Frameworks & Callbacks

Android & Java provide many


frameworks
Android
Android Activity framework
controls the main thread

See developer.android.com/training/multiple-threads/communicate-ui.html
23

Frameworks & Callbacks

Android & Java provide many


frameworks
Android
Android Activity framework
controls the main thread

An applications lifecycle
methods are called back by
Androids Activity framework
e.g., onCreate(), onStart(),
onStop(), onDestroy(), etc.

See developer.android.com/training/basics/activity-lifecycle
24

Frameworks & Callbacks

Android & Java provide many


frameworks
Android
Android Activity framework
controls the main thread

final Button button =


(Button) findViewById
(R.id.loadButton);
button.setOnClickListener
(new OnClickListener() {
@Override
public void onClick(View v) {
... A GUI component sending an
}});
event to its registered listener

An applications lifecycle
methods are called back by
Androids Activity framework
A listener for button clicks is
called back by Androids GUI
framework
GUI Component

(a button)

25

public void
onClick(View v){
...
}

ClickListener
Object

Frameworks & Callbacks

Android & Java provide many


frameworks
Android
Java
A Thread calls back on the
run() hook method of a
Runnable

See docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html
26

Frameworks & Callbacks

Android & Java provide many


frameworks
Android
Java
A Thread calls back on the
run() hook method of a
Runnable
The ExecutorService calls back
to the call() hook method of a
Callable

Thread
1.submit(callable)
submit()

run()
2.offer()
WorkerThreads
callable
WorkQueue

3.take()
4.call()
callable

ExecutorService

See docs.oracle.com/javase/tutorial/essential/concurrency/executors.html
27

Frameworks & Callbacks

Most code you write in this class


will use one or more frameworks
Some of your solutions will
implement your own framework

All Android apps run inside28


of one or more frameworks

Frameworks & Callbacks

Frameworks use Javas inheritance


& polymorphism features

Abstraction

OOP

Polymorphism

29

Inheritance

Frameworks & Callbacks

Frameworks use Javas inheritance


& polymorphism features, e.g.
Abstract classes & interfaces
provide extension mechanisms

public interface Runnable {


public void run();
}

30

Frameworks & Callbacks

Frameworks use Javas inheritance


& polymorphism features, e.g.
Abstract classes & interfaces
provide extension mechanisms
Concrete implementations of
abstract classes & interfaces
are passed to framework

public interface Runnable {


public void run();
}
new Thread(new Runnable() {
public void run() {
System.out.println
("hello world");
}
}.start();

Anonymous instance of an
anonymous inner class

31

Frameworks & Callbacks

Frameworks use Javas inheritance


& polymorphism features, e.g.
Abstract classes & interfaces
provide extension mechanisms
Concrete implementations of
abstract classes & interfaces
are passed to framework

public interface Runnable {


public void run();
}
new Thread(new Runnable() {
public void run() {
System.out.println
("hello world");
}
}.start();

Anonymous instance of
a lambda expression

new Thread(() ->


System.out.println
("hello world")).start();

32

Overview of
Java Inheritance
33

Overview of Java Inheritance


A Java class can derive from another
class using the extends keyword

package java.util;
/ This class would reside in
public class Stack<E> {
extends Vector<E> {
...

See docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
34

Overview of Java Inheritance


A Java class can derive from another
class using the extends keyword
A subclass inherits methods &
data members from its (one &
only) super class

package java.util;
/ This class would reside in
public class Stack<E> {
extends Vector<E> {
...

This subclass is said to


derive from the superclass

See docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
35

Overview of Java Inheritance


Methods inherited from super class
can be used for three main purposes

package java.util;
/ This class would reside in
public class Stack<E> {
extends Vector<E> {

36

Overview of Java Inheritance


Methods inherited from super class
can be used for three main purposes
To augment the subclass API
A subclass inherits methods
& data members of its
superclass

package java.util;
/ This class would reside in
public class Stack<E> {
extends Vector<E> {

37

Overview of Java Inheritance


Methods inherited from super class
can be used for three main purposes
To augment the subclass API
A subclass inherits methods
& data members of its
superclass

package java.util;
/ This class would reside in
public class Stack<E> {
extends Vector<E> {

e.g.,

e.g., Stack inherits


isEmpty() from Vector

Stack<Integer> s =
new Stack<>();
if(!s.isEmpty())
s.pop();

This Stack class uses so-called


38implementation inheritance

Overview of Java Inheritance


package java.util;
Methods inherited from super class
can be used for three main purposes / This class would reside in
public class Stack<E> {
To augment the subclass API
extends Vector<E> {
A subclass inherits methods
& data members of its superclass

A method can be invoked


on an object instance

e.g.,
Stack<Integer> s =
new Stack<>();
if(!s.isEmpty())
s.pop();

39

Overview of Java Inheritance


Methods inherited from super class
can be used for three main purposes
To augment the subclass API
To implement subclass methods
A subclass may add new
methods & data members

package java.util;
/ This class would reside in
public class Stack<E> {
extends Vector<E> {
public Object push(E e){
addElement(e);
return e;
}

40

Overview of Java Inheritance


Methods inherited from super class
can be used for three main purposes
To augment the subclass API
To implement subclass methods
A subclass may add new
methods & data members

package java.util;
/ This class would reside in
public class Stack<E> {
extends Vector<E> {
public Object push(E e){
addElement(e);
return e;
}

The Stacks push() method is


implemented via Vectors
addElement() method

41

Overview of Java Inheritance


package java.util;
Methods inherited from super class
can be used for three main purposes / This class would reside in
public abstract class
To augment the subclass API
AbstractMap<K,V> ... {
public abstract
To implement subclass methods
Set<Entry<K,V>> entrySet();
To override super class methods in
...
the subclass

A subclass may define methods


with the same signatures as
super class methods

public HashMap<K,V> extends


AbstractMap<K,V> {
public Set<Entry<K,V>>
entrySet() {
...
}
...

42

Overview of Java Inheritance


package java.util;
Methods inherited from super class
can be used for three main purposes / This class would reside in
public abstract class
To augment the subclass API
AbstractMap<K,V> ... {
public abstract
To implement subclass methods
Set<Entry<K,V>> entrySet();
To override super class methods in
...
the subclass

A subclass may define methods


with the same signatures as
super class methods
These methods override the
original methods

public HashMap<K,V> extends


AbstractMap<K,V> {
public Set<Entry<K,V>>
entrySet() {
...
}
...

43

Overview of Java Inheritance


package java.util;
Methods inherited from super class
can be used for three main purposes / This class would reside in
public abstract class
To augment the subclass API
AbstractMap<K,V> ... {
public abstract
To implement subclass methods
Set<Entry<K,V>> entrySet();
To override super class methods in
...
the subclass

A subclass may define methods


with the same signatures as
super class methods
These methods override the
original methods

HashMaps entrySet() method overrides


HashMaps
AbstractMaps entrySet() abstract method
public HashMap<K,V> extends
AbstractMap<K,V> {
public Set<Entry<K,V>>
entrySet() { ... }
...

Method overriding
44is covered shortly

Overview of Java Inheritance


All classes inherit from the
java.lang.Object super class

package java.lang;
in
public class Object {
...
public final void wait();
public final void notify();
public final void notifyAll();
public final boolean equals
(Object o);
...

See docs.oracle.com/javase/7/docs/api/java/lang/Object.html
45

Overview of Java Inheritance


All classes inherit from the
java.lang.Object super class
If you do not explicitly specify a
super class, your class will inherit
from java.lang.Object implicitly

package java.lang;
in
public abstract class Process {
...
public abstract int waitFor()
...;
...

46

Overview of Java Inheritance


All classes inherit from the
java.lang.Object super class
If you do not explicitly specify a
super class, your class will inherit
from java.lang.Object

Object

The root of every classs inheritance


hierarchy is thus java.lang.Object
All objects, including arrays,
implement the methods of this
class

wait()
notify();
notifyAll();
equals();

Process
waitFor()

47

Overview of Java Inheritance


java.lang.Object defines.equals()
If operator== is used to compare
the equality of two objects it
returns true if the two objects have
the same memory address

Object
wait()
notify();
notifyAll();
equals();

Process
waitFor()

48

Overview of Java Inheritance


java.lang.Object defines.equals()
If operator== is used to compare
the equality of two objects it
returns true if the two objects have
the same memory address
Conversely, if you use .equals() to
compare for equality, a subclass
can override this method to do
other things
e.g., check for equal values in
a collection or string

Object
wait()
notify();
notifyAll();
equals();

Process
waitFor()

49

Overview of Java
Polymorphism
We examine a concrete &50
complete example in detail

Overview of Java Polymorphism

A subclass can override certain


methods from a super class

AbstractMap<K,V>

entrySet()
put()

Any non-final & non-static51


methods can be overridden

Overview of Java Polymorphism

A subclass can override certain


methods from a super class
e.g., the map class hierarchy in
the Java Collection framework

AbstractMap<K,V>

entrySet()
put()

Returns a set view of


all the mappings
contained in a map
Associates the specified value
with the specified key in a map

See docs.oracle.com/javase/7/docs/api/java/util/AbstractMap.html
52

Overview of Java Polymorphism

A subclass can override certain


methods from a super class
e.g., the map class hierarchy in
the Java Collection framework

TreeMap<K,V>

entrySet()
put()

AbstractMap<K,V>

entrySet()
put()

HashMap<K,V>

entrySet()
put()

Concurrent
HashMap<K,V>

entrySet()
put()

Subclasses of AbstractMap override53put() & entrySet() in different ways

Overview of Java Polymorphism

The implementation of these


methods is selected at run-time
based on the objects type

Could be HashMap, TreeMap,


ConcurrentHashMap, etc.

public static void main


(String[] args) {
SimpleAbstractMap
<String, Integer> map =
makeMap(args[0]);
map.put("I", 1);
map.put("am", 2);
map.put("Ironman", 7);
for(Map.Entry<String, Integer> s
: map.entrySet())
System.out.println
("key = " + s.getKey() +
" value = " + s.getValue());
}

See github.com/douglascraigschmidt/CS251/tree/master/ex/DynamicBinding
54

Overview of Java Polymorphism

Every Java object keeps track of


its virtual table (vtable), which
dispatches methods dynamically
Java implements virtual
methods like C++

AbstractMap
0

Pointer to vtable

Pointer to method1

4
8

keySet field1

Pointer to method2

values field2

Pointer to methodn

HashMap
0

Pointer to vtable

Pointer to method1

4
8

keySet field1

Pointer to method2

values field2

Pointer to methodn

12
16
20

table field1

other fields

entrySet field2
size field3

Method1 bytecode
Method2 bytecode
Methodn bytecode

Method1 bytecode
Method2 bytecode
Methodn bytecode

See en.wikipedia.org/wiki/Dynamic_dispatch
55

Java Collections
Framework
56

Overview of the Java Collections Framework


The JCF is a unified architecture
for representing & manipulating
collections

See docs.oracle.com/javase/8/docs/technotes/guides/collections
57

Overview of the Java Collections Framework


The JCF is a unified architecture
for representing & manipulating
collections
A collection is an object that
represents a group of objects
e.g., an ArrayList<Point>

Each element in the collection is


actually a reference to another object

58

Overview of the Java Collections Framework


The JCF is a unified architecture
for representing & manipulating
collections
A collection is an object that
represents a group of objects
Collections can be accessed
& manipulated independently
of their representation
e.g., the List interface can be
implemented as either a
LinkedList or as an ArrayList

59

Overview of the Java Collections Framework


JCF is based on more than a
dozen collection interfaces

The collection interfaces contain two groups


java.util.Collection
java.util.Set
java.util.SortedSet
java.util.NavigableSet
java.util.Queue
java.util.concurrent.BlockingQueue
java.util.concurrent.TransferQueue
java.util.Deque
java.util.concurrent.BlockingDeque

60

Overview of the Java Collections Framework


JCF is based on more than a
dozen collection interfaces

The collection interfaces contain two groups


java.util.Map
java.util.SortedMap
java.util.NavigableMap
java.util.concurrent.ConcurrentMap
java.util.concurrent.
ConcurrentNavigableMap

61

Overview of the Java Collections Framework


JCF is based on more than a
dozen collection interfaces
Includes implementations of
these interfaces & algorithms
to manipulate them

Inter
face

Hash
Table

Set

HashSet

Resize
Array

Balanced
Tree

Linked List

Linked
Hash
Set

Tree
Set

List

Array
List

LinkedList

Deque

Array
Deque

LinkedList

Map

HashMap

TreeMap

Hash Table+
Linked List

Linked
Hash
Map

JCF implementations use inheritance,62polymorphism, & generics extensively

Overview of the Java Collections Framework


JCF has several key benefits
Reduces programming effort
By providing data structures
& algorithms so developers
dont need to write them

63

Overview of the Java Collections Framework


JCF has several key benefits
Reduces programming effort
Increases performance
By providing highly optimized
implementations of data
structures & algorithms

64

Overview of the Java Collections Framework


JCF has several key benefits
Reduces programming effort
Increases performance
Enables interoperability among
unrelated APIs
By establishing a common
means to pass collections
back & forth

65

Overview of the Java Collections Framework


JCF has several key benefits
Reduces programming effort
Increases performance
Enables interoperability among
unrelated APIs
Reduces effort in designing &
learning new APIs
By not requiring learning
multiple ad hoc collection APIs

66

Overview of the Java Collections Framework


JCF has several key benefits
Reduces programming effort
Increases performance
Enables interoperability among
unrelated APIs
Reduces effort in designing &
learning new APIs
Fosters software reuse
By providing standard interfaces
for collections & algorithms that
manipulate them

67

Overview of the Java Collections Framework


Common JCF classes
An ArrayList is a variable-sized
list of items similar to a built-in
Java array

import java.util.ArrayList;
...
List<String> myList =
new ArrayList<>();
myList.add("foo");
myList.add("bar");
myList.add("foobar");
// List stores object of type
// java.lang.String, so no need
// to cast item back to String
String itemOne = myList.get(0);
myList.remove(0);

See docs.oracle.com/javase/8/docs/technotes/guides/collections
68...

Overview of the Java Collections Framework


Common JCF classes
An ArrayList is a variable-sized
list of items similar to a built-in
Java array
A HashMap stores key/value pairs

import java.util.HashMap;
...
HashMap<String, Foo> myMap =
new HashMap<>();
Foo f1 = new Foo();
Foo f2 = new Foo();
myMap.put("one", f1);
myMap.put("two", f2);
if (f2 == myMap.get("two"))
...
else if (f1 ==
myMap.get("one"))
...

69

Overview of the Java Collections Framework


These are the concurrent-aware interfaces:
Concurrent collections provide
features that are frequently needed
BlockingQueue
in concurrent programming
TransferQueue
BlockingDeque
ConcurrentMap
ConcurrentNavigableMap

70

Overview of the Java Collections Framework


Concurrent-aware classes include
Concurrent collections provide
features that are frequently needed
LinkedBlockingQueue
in concurrent programming
ArrayBlockingQueue
PriorityBlockingQueue
DelayQueue
SynchronousQueue
LinkedBlockingDeque
LinkedTransferQueue
CopyOnWriteArrayList
CopyOnWriteArraySet
ConcurrentHashMap

Java concurrency covered in CS 282 (www.dre.vanderbilt.edu/~schmidt/cs282)


71

Iterating Through
Collections in Java
72

Iterating Through Collections in Java

Java has several ways to loop


through collections
The conventional for loop
used in C/C++

ArrayList<String> myStrings =
new ArrayList<>();
myStrings.add("a");
myStrings.add("b");
myStrings.add("c");
for(int i = 0;
i < myStrings.size();
i++) {
System.out.println
(myStrings.get(i));
}

Venerable,73
but crufty

Iterating Through Collections in Java

Java has several ways to loop


through collections
The conventional for loop
used in C/C++
An enhanced for-each loop for
iterating over collections

ArrayList<String> myStrings =
new ArrayList<>();
myStrings.add("a");
myStrings.add("b");
myStrings.add("c");
for (String aString :
myStrings) {
System.out.println(aString);
}

Very clean
74& concise

Iterating Through Collections in Java

Java has several ways to loop


through collections
The conventional for loop
used in C/C++
An enhanced for-each loop for
iterating over collections
An Iterable interface

ArrayList<String> myStrings =
new ArrayList<>();
myStrings.add("a");
myStrings.add("b");
myStrings.add("c");
for (Iterator<String> it =
myStrings.iterator();
it.hasNext();
) {
System.out.println
(it.next());
}

Pattern-oriented, but overly verbose


compared to for-each loop
75

Iterating Through Collections in Java

Java has several ways to loop


through collections
The conventional for loop
used in C/C++
An enhanced for-each loop for
iterating over collections
An Iterable interface
The forEach() method

ArrayList<String> myStrings =
new ArrayList<>();
myStrings.add("a");
myStrings.add("b");
myStrings.add("c");
myStrings
.stream()
.forEach
(aString ->
System.out.println
(aString));

Very powerful, but requires knowledge


76of Java lambda expressions & streams

You might also like