OO, Java and the Swing Classes

Download Report

Transcript OO, Java and the Swing Classes

Object Oriented Programming
Charles E. Hughes
[email protected]
http://www.cs.ucf.edu/~ceh
Professor, School of EECS
University of Central Florida
7/16/2015
© Charles E. Hughes 2000
1
Day#1
7/16/2015
© Charles E. Hughes 2000
2
Basic Information
7/16/2015
© Charles E. Hughes 2000
3
Who and Where?
• Instructor:
Charles E. Hughes; CSB 206; (407) 823 2762; [email protected]
• Meeting Times and Place:
TR 10:00 to 11:15 in CL1 117
• Office Hours:
T 1:30 to 3:00; W 10:00 to 11:30; R 2:30 to 4:00 CSB 206
• Text:
Object-Oriented Software Development Using Java
Xiaoping Jia, Addison-Wesley, 2000.
7/16/2015
© Charles E. Hughes 2000
4
Other Java Learning Resources
• The Java Programming Language, Third Edition
K. Arnold, J. Gosling, D. Holmes, Addison-Wesley, 2000
• Thinking in Java, 2nd Edition
Bruce Eckel, Prentice Hall, 2000
also on-line at http://www.eckelobjects.com/
• The Java Tutorial Second Edition: Object-Oriented Programming
for the Internet
Mary Campione, Kathy Walrath, Addison-Wesley, 1998
also on-line at http://java.sun.com/docs/books/tutorial/index.html
• Design Patterns: Elements of Reusable Object-Oriented Software
Gamma, Helm, Johnson & Vlissides, Addison-Wesley, 1995
7/16/2015
© Charles E. Hughes 2000
5
Software Development
• Java IDEs:
JBuilder 3.5
http://www.borland.com/jbuilder/foundation/
Forte for Java CE 1.0 http://www.sun.com/forte/ffj/ce/
Need support for Java 2 -- jdk1.2.2 or later, preferably
jdk1.3, though JBuilder is packaged with jdk1.2.2.
• Smalltalk IDE
Squeak 2.7 (Smalltalk) http://www.squeak.org/
Not required at present
7/16/2015
© Charles E. Hughes 2000
6
Why JBuilder 3.5?
• It’s Free
• It has a GUI designer that does not trash your program; no
magical comments
• It has one of the best help systems around; you can peruse the
Java class files with great ease
• It includes a very slick interface for running both applets and
applications
• It can be configured for any JDK, even the pared-down class
hierarchy used to create software for pda’s –
Note: the free JBuilder can only manage one JDK at a time. The
Pro version manages multiple JDK’s on a per-project basis.
7/16/2015
© Charles E. Hughes 2000
7
Evaluation
• Exams: Midterm and Final for about 50% of grade
• Programming Assignments: Four of five for about 20%
of grade; Adhere to Deadlines
• Team Programming Project: One for about 20% of
grade
• Wild Card: About 10% based on exercises and inclass participation
7/16/2015
© Charles E. Hughes 2000
8
Some Guiding Principles
Motherhood and Apple Pie
Included at No Extra Cost
7/16/2015
© Charles E. Hughes 2000
9
Programming in the Small
• Code is developed by one programmer
– Maybe a small close-knit group
• One person can understand the entire system
– To them the system is self-documenting
– The creator is the maintainer
• Designed to solve a particular (singular) problem
• System does not have a long life cycle
• The biggest problem is getting it done on time
7/16/2015
© Charles E. Hughes 2000
10
Programming in the Large
• Developed by a large team of programmers with a lot of input
from management
• Nobody really knows what is really going on inside all parts of
the system
– Everybody has their own little piece
• The system is designed to solve a “systems” level problem
• Ideally, the system will be around for a long time
• Communication (developers to customers & developers to
developers) is the biggest problem
7/16/2015
© Charles E. Hughes 2000
11
Attributes of Large Systems
• “The complexity of software systems we are asked to develop is
increasing, yet there are basic limits on our ability to cope with
this complexity.” – Booch
• Hierarchies
– Manageable complex systems are commonly hierarchical
• Locality
– Intracomponent dwarfs intercomponent communication
• Prototypes
– Successful systems evolve from simpler working systems
7/16/2015
© Charles E. Hughes 2000
12
Desirable System Qualities
•
Useful – meets needs
•
Timely – shipped when expected
•
Reliable – within tolerable limits
•
Easy to use – by intended audience
•
Efficient – including good algorithms
•
Maintainable – flexible, simple, readable
– Over 40% of maintenance is change in user requirements
•
Reusable – by you and others
– These are the two primary issues for this course, and the ones most
effectively addressed by the OO Paradigms
7/16/2015
© Charles E. Hughes 2000
13
Maintainability Factors
• Flexibility
– Easily changeable; limited impact from changes
• Simplicity
– All complex systems have errors; dividing a system into
simpler components reduces or at least manages complexity
• Readability
– Clarity is a great aid to maintainability; simple, consistent
style aids understandability
7/16/2015
© Charles E. Hughes 2000
14
Internal Quality Factors
• Perceptible to designers and implementers
• Programmer's view of quality
– Modularity
– Readability / understandability
– Levels of abstraction (information hiding)
– Low coupling of modules
– High cohesion of modules
7/16/2015
© Charles E. Hughes 2000
15
External Qualities
• Perceptible to users and clients
• User’s view of quality Correct – as defined by
requirements and specs.
– Correct – meets specifications
– Robust – functions under the abnormal
– Extendible – adapts easily to new specifications
– Reusable – in extensions and other projects
– Compatible/composable – with other components
7/16/2015
© Charles E. Hughes 2000
16
More External Qualities
• Efficient
– requires an acceptable amount of resources
• Portable
– can be used on different machines / domains
• Verifiable
– can easily prepare acceptance process, particularly test data
• Maintains Integrity (security / protection)
– can be assured that software system protects its various
components (programs, data, documents) and the system on which
it’s deployed against unauthorized access and modification
• Easy to use
– has an intuitive interface – relates to problem domain
7/16/2015
© Charles E. Hughes 2000
17
Software Phases
•
Conceptualization
– Requirements – informal description of what is needed; often includes
prototype to help resolve issues
– Specifications – formal requirements; can be legal document; often includes
walkthrough with client, moderated by QA staff
•
Analysis and Modeling – identifying the software components
•
Design – designing the components and their relationships
•
Implementation – making it real
•
Integration – putting the parts together with each other and existing
components
•
Maintenance – fixing, improving, adapting
7/16/2015
© Charles E. Hughes 2000
18
Focus of Course
• We will focus on
– Analysis and Modeling
– Design
– Implementation
• This is an iterative part of the process. Design often
uncovers missing components. Of course, any of
these phases can drive us all the ways back to
requirements, but we will focus on the tighter loop
above.
7/16/2015
© Charles E. Hughes 2000
19
Modularity
• A system is a collection of highly cohesive, but
loosely coupled modules
• Cohesiveness is a measure of intra-module
relatedness
• Coupling is a measure of module interdependency
– In process-oriented programming, modules are procedures
– In object-oriented programming, modules are classes and
packages
7/16/2015
© Charles E. Hughes 2000
20
Modularity Questions
• Decomposable – how to divide?
• Composable – how to make it possible to put pieces
together easily?
• Understandable – how to make it easy to follow?
• Continuity – how to guarantee that small specification
changes lead to isolated code changes?
• Isolation/Protection – how to prevent changes from
propagating far; supports continuity
7/16/2015
© Charles E. Hughes 2000
21
Principles for Modularity
• Reality – design corresponds to real world;
software modules correspond to design modules
• Few interfaces – don’t talk to too many others
• Weak coupling – don’t disclose too much
• Explicit interfaces – easy to see who talks to whom
• Information hiding – clear, limited and explicit access
– Improves continuity since clients don’t know too much
7/16/2015
© Charles E. Hughes 2000
22
Open / Closed Principle
• Open Module
– Can be extended, e.g., with new parts and services
• Closed Module
– Can be used by other modules (it’s complete)
• We want modules simultaneously open and closed
– This supports testing and prototype demos, even while
development is occurring
7/16/2015
© Charles E. Hughes 2000
23
Basic Vocabulary
• Abstraction
– Selective examination of certain aspects of a problem
– The goal is to isolate those aspects that are important for some
purpose and suppress those that are unimportant
– Many different abstractions of the same thing are possible,
depending on the purposes for which they are made
• Model
– An abstraction used to understand or reason about some real object
– Omits nonessential details and is at granularity appropriate for its
purposes
• Methodology (in software engineering)
– A process for the organized production of software using a
collection of predefined techniques and notional conventions
7/16/2015
© Charles E. Hughes 2000
24
Modeling
• Designing a system is about modeling the problem
space (real world)
• Issues include
– What are the components of the real world?
– How do they behave?
– How do they interact?
– What can we ignore?
7/16/2015
© Charles E. Hughes 2000
25
Process versus Object
• Processes
– Data structures are designed to fit processes
– Processes and data structures conceived in solution space
• Objects
– Objects are from the problem space
– They survive changes in functionality
7/16/2015
© Charles E. Hughes 2000
26
Proverb (Bertrand Meyer)
Ask not what the system does;
Ask what it does it to!
7/16/2015
© Charles E. Hughes 2000
27
Insights #1 (Grady Booch)
We cannot hope to reduce the
complexity of our problems.
Abstraction and Information Hiding are
software engineering's best hopes to
date for managing the complexity of our
solutions to problems.
7/16/2015
© Charles E. Hughes 2000
28
Insights #2 (Bertrand Meyer)
In the evolution of a system, the
functions tend to be the most volatile
parts.
A successful system will soon be asked
to perform new tasks.
7/16/2015
© Charles E. Hughes 2000
29
Insights #3 (Sapir / Whorf)
We see and hear and otherwise
experience very largely as we do
because the language habits of our
community predispose certain choices
of interpretation.
7/16/2015
© Charles E. Hughes 2000
30
Language’s Influence
• The Whorfian hypothesis argues for using OO languages when
we commit to OO design.
• Other comments on the influence of language on thought
– In order to internalize abstractions, humans appear to need a name
for these concepts, strategies or processes.
– In algorithm design, we are enormously more effective once we learn
to categorize strategies as divide and conquer, dynamic
programming and greedy.
– OO design has its own strategies, called patterns, which allow us to
categorize common approaches to the design of program
components.
7/16/2015
© Charles E. Hughes 2000
31
Exercise #1
•
How would you design a medical reimbursement program which
categorizes procedures as follows?
–
None (e.g., $0.00 for procedure 137)
–
Fixed (e.g., $25 for procedure 22)
–
Percentage (e.g., 75% of charge for surgical procedure 103)
–
Stop-loss (e.g., 50% of charge up to a max of $750)
•
You would, of course, associate each procedure number with a
reimbursement strategy. But, what are these strategies? (code
numbers, objects of some sort, …)
•
Be ready to discuss this at next meeting.
7/16/2015
© Charles E. Hughes 2000
32
Structured Programming
Top Down Design
7/16/2015
© Charles E. Hughes 2000
33
Top Down Perspective
• Process oriented
• Design based on functional requirements
• Data structures exist to support algorithms
– Programs = Algorithms + Data Structures
7/16/2015
© Charles E. Hughes 2000
34
Top Down Advantages
• It is logical, well-organized thought discipline
• Encourages orderly development
• Gets the design process started
– Helps designer find a way though apparent complexity that
characterizes the initial stages of system design
• Remains a useful paradigm for small programs
7/16/2015
© Charles E. Hughes 2000
35
Top Down Disadvantages
• Fails to take into account the evolutionary nature of systems
• Data structure aspect is relegated to secondary role
• Does not promote reusability
– Elements tend to be narrowly adapted to the subproblem that led to
their development, they are not naturally general
• Early commitment to runtime events and the order in which
actions will be executed
– Commits to temporal ordering of events
• Assumes all programs have a top
– Is radically affected by choices at the top
7/16/2015
© Charles E. Hughes 2000
36
Day#2
7/16/2015
© Charles E. Hughes 2000
37
Object-Oriented Thinking
7/16/2015
© Charles E. Hughes 2000
38
OO Approach
• Base the structure of the software on the objects and not on the
actions
• In structured programming
– define what must be done
– define the data structures
• In OO
– Define the objects
• group like object together
– define what they do
7/16/2015
© Charles E. Hughes 2000
39
OO Advantages
• Ability to model the salient components of the system
• Predisposed to a modular implementation
• Public interfaces, private actions
• Software Reuse
7/16/2015
© Charles E. Hughes 2000
40
OO Disadvantages
• Interactions can be very complex
• Difficult to select “correct” objects
– Level of resolution
• Inherent parallelism of actions can be hard to visualize
and can lead to synchronization errors
• More up front design time is needed
• Can be tedious to chase messages
7/16/2015
© Charles E. Hughes 2000
41
Process versus Object
• Traditional: Emphasizes Processes
– Data structures are designed to fit processes.
– Processes and data structures are conceived in solution space.
• Object-Oriented: Emphasizes Objects
– Objects are from the problem space.
– They survive changes in functionality.
– Interpretation of messages is by objects.
– Objects are easier to classify than operations.
7/16/2015
© Charles E. Hughes 2000
42
Perspective from Real World
• Object
– An object is anything in the problem space that is distinctly
identifiable
• Class
– A class is a set of objects with similar characteristics and
behaviors. Objects are instances of their class
7/16/2015
© Charles E. Hughes 2000
43
Perspective from Model
• Object
– An object has a unique identity, a state and a set of behaviors
• Class
– Characterizes the structure of states and behaviors that are
shared by all its instances
7/16/2015
© Charles E. Hughes 2000
44
Abstract data Type (ADT)
• An abstract data type specification describes a class
of data structures not by an implementation, but by a
list of services available on instances of a type, and
the formal semantics of those services.
• An ADT is a behavioral specification for objects
• A class is an implementation of an ADT
• An object is an instance of a class
7/16/2015
© Charles E. Hughes 2000
45
Abstractions Depend on Use
• An Abstraction denotes the essential characteristics of an object
that distinguish it from all other kinds of objects and thus provide
crisply defined conceptual boundaries, relative to the perspective
of the viewer.
• DOT’s abstraction of my car is quite different than the abstraction
of my road runner that a game maker may want.
– To a DOT data base system analyst
• Attributes:
– Year/Make/Model, Color, License #, Owner, VID, …
• Protocol:
– Owner, Owner:, License, License:, etc.
– To a game software expert
• Attributes:
– Display, Speed, Maneuverability, Condition,…
• Protocol:
– Show, Speed, Speed:, Condition, Crash, etc.
7/16/2015
© Charles E. Hughes 2000
46
Abstractions in Daily Life
• We employ abstraction daily by identifying the objects
and operations that exist at each level of interaction.
Thus, when
– Driving a car - we consider the accelerator, gauges ...
– Repairing an engine - we consider lower level objects such as
the fuel pump, carburetor and distributor.
• A program that implements a model of reality (and all
of them should) can be viewed as a set of models that
interact with one another.
7/16/2015
© Charles E. Hughes 2000
47
Objects
• Objects have
– States (attributes, parts) characterized by variables (named
parts)
– Services (behaviors, responsibilities) characterized by
methods (operations)
– Features characterized by the combination of state and
services
• The services of an object represent its contractual
commitment or protocol
7/16/2015
© Charles E. Hughes 2000
48
Classes
• Classes
– Are templates (factories) used to create objects
– Define the common structure and services of their instances
(objects of the class)
– Can provide additional services and states that are not
associated with objects, but rather with the family of objects
defined by the class
• You can build object-based systems without classes,
e.g., by prototyping – but that’s another story
7/16/2015
© Charles E. Hughes 2000
49
Example using Class Notation
Rectangle
Rectangle
int length
length
int width
width
public int area()
area
public int perimeter()
perimeter
7/16/2015
© Charles E. Hughes 2000
Rectangle
50
Example using Object Notation
r1 : Rectangle
r2 : Rectangle
length = 10
length = 7
width = 12
width = 5
Rectangle r1 = new Rectangle(10, 12); //constructor
Rectangle r2 = new Rectangle(7, 5); //constructor
int area1 = r1.area(); // area service
int perimeter2 = r2.perimeter(); // perimeter service
7/16/2015
© Charles E. Hughes 2000
51
Another View of Objects
length
width
10
12
private
copy of
data
area()
perimeter
shared
code
length
width
area()
perimeter
7/16/2015
© Charles E. Hughes 2000
7
5
private
copy of
data
shared
code
52
Abstraction as Contract
• The contractual commitment or protocol of an object
(module) captures its essence
• An object provides a service, and always will provide
that service, even if it changes how the service is
provided. This is the object’s contractual commitment.
• A client uses an object based on its contractual
commitment, not on its implementation.
7/16/2015
© Charles E. Hughes 2000
53
Encapsulation
7/16/2015
© Charles E. Hughes 2000
54
Encapsulation
• An object is encapsulated if its implementation and
interface (contractual commitment) are separated, and
its clients are only aware of its interface.
• Encapsulation enforces the desirable property of
abstraction in which object use is based on services
(the WHAT) not implementation (the HOW).
• Even querying the state of an object can and should
require an accessor method
• Enforces “Need to Know” policies
7/16/2015
© Charles E. Hughes 2000
55
A Useful Encapsulation
Point2D
setXY
getX
getY
Provide required services independent of state
representation (Cartesian or polar here)
7/16/2015
© Charles E. Hughes 2000
56
Java Point2D
public class Point2D {
private double r, theta;
public void setXY (double x, double y) {
r = Math.sqrt((x*x)+(y*y));
theta = Math.atan2(y,x);
}
public double getX() {
return r*Math.cos(theta);
}
public double getY() {
return r*Math.sin(theta);
}
}
public class Point2D {
private double x, y;
public void setXY (double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
}
Note: Some “hidden” aspects can be deduced by
observation of loss of precision. C’est la vie.
7/16/2015
© Charles E. Hughes 2000
57
Contractual Interfaces as ADTs
• An ADT is an interface without an implementation.
Java supports interfaces, as well as abstract classes,
which can include some method implementations.
• A class can implement one or more interfaces, each of
which adds to its contractual commitment.
• Thread is an example of a Runnable class – its
instances provide a run() service.
Runnable
Run()
7/16/2015
Thread
Run()
© Charles E. Hughes 2000
58
Day#3
7/16/2015
© Charles E. Hughes 2000
59
Polymorphism
7/16/2015
© Charles E. Hughes 2000
60
Polymorphism
• Services are provided by multiple providers, each of
whom honors the contractual commitment of some
common interface.
• It is important that at some semantic level they all
perform the same action, just in their own special way.
• In Java, all objects respond to the message
“toString()” Clearly a List of names does this
differently than an Integer.
7/16/2015
© Charles E. Hughes 2000
61
Polymorphism among Widgets
// paint this widget and all it contains
// each widget determines how it paints itself
paint (Graphics g) {
paintComponent(g); // paint self (sometimes done by peer)
paintBorder(g); // if have border, paint it in appropriate style
paintChildren(g); // iterates across children, asking each to paint
}
7/16/2015
© Charles E. Hughes 2000
62
Smalltalk Widget Display
display
self displayBorder.
self displayView.
"each view ‘knows’ its offset in enclosing view"
subViews do: [:aSubView | aSubView display]
7/16/2015
© Charles E. Hughes 2000
63
The role of Dynamic Binding
• A reference variable may refer to objects of differing
classes at various times during execution. Dynamic
binding awaits the execution-time (run-time) reference
to bind a call to its implementing code.
• Dynamic binding is required by our widget example
because a container only knows that it has children
who understand the message “paint(Graphics g)”
• Polymorphic message passing (method invocation)
and dynamic binding are central to OOP’s power and
elegance.
7/16/2015
© Charles E. Hughes 2000
64
Polymorphism in Java
• A method’s signature is made up of
– name
– parameters (number, order and type)
– return type
• not considered for overloading purposes in Java
• Two common usages
– Same class and name, different parameters
List() {…}
List(int size) {…}
add(Object element) { …}
add(Collection collection) { …}
– Override a parent’s method
• Must have the same signature
public class Object {…}
public String toString() { return
}
public class Employee extends Object {…}
public String toString() { return name; }
}
7/16/2015
© Charles E. Hughes 2000
65
Inheritance
7/16/2015
© Charles E. Hughes 2000
66
Object-based – Object-Oriented
• Object-Based
– Provides
•
•
•
•
classes
encapsulation
binding of operations to types
polymorphism
– Lacks
• inheritance
• benefits from dynamic binding, unless no type checking
• Object-Oriented
– Provides all that is Object-Based plus
• inheritance
• dynamic binding, in presence of type checking
• Some OO languages support both static and dynamic binding
– need dynamic for effective use of collections of related objects
– C++ has notions of non-virtual, virtual and pure virtual
– Java is dynamic, but requires casts to avoid compile-time errors
7/16/2015
© Charles E. Hughes 2000
67
Inheritance
• Inheritance, the ability of a class to inherit capabilities and
features form a parent class, is what distinguishes Object-based
from Object-Oriented.
• Inheritance defines an is-a relationship. This is different from
aggregation which forms a has-a relationship.
• An inheriting class is called a subclass. Its parent is its
superclass.
• Inherit is also called extend, reflecting our principle that a child
class should never restrict the services of its parent. To do so
destroys the is-a relationship.
7/16/2015
© Charles E. Hughes 2000
68
Swing Inheritance Hierarchy#1
Object
Component
Container
JComponent
Panel
Applet
JApplet
7/16/2015
© Charles E. Hughes 2000
69
Swing Inheritance Hierarchy#2
7/16/2015
© Charles E. Hughes 2000
70
Swing Inheritance Hierarchy#3
7/16/2015
© Charles E. Hughes 2000
71
Part of Smalltalk Collection
7/16/2015
© Charles E. Hughes 2000
72
Java Collection – Details Later
Object
AbstractCollection // implements Collection
// add(Object), addAll(Collection), clear(), contains(Object), containsAll(Collection),
// equals(Object), hashCode(), isEmpty(), iterator(), remove(Object),
// removeAll(Collection), retainAll(Collection), size(), toArray(), toString()
AbstractSet // implements Set
HashSet
TreeSet implements SortedSet
AbstractList // implements List
AbstractSequentialList
LinkedList
ArrayList
Vector (actually this is a bit old fashion)
Stack // BARF!!!!!!!!
AbstractMap // implements Map
HashMap
TreeMap
WeakHashMap
Arrays // utilities for all arrays
BitSet
Collections // utilities for all collection classes
Dictionary
Hashtable
Properties
7/16/2015
© Charles E. Hughes 2000
73
Day#4
7/16/2015
© Charles E. Hughes 2000
74
Class Relationships
• Inheritance – is-a relation
• Association – general relationship; e.g., uses, creates
• Aggregation – has-a relation; or from contained object
this is the part-of relation; both lead to part-whole
relation
• Composition – exclusive ownership form of
aggregation
rules
Company
1
CEO
1
Employee
1
7/16/2015
works for
© Charles E. Hughes 2000
1..*
75
Composition versus Inheritance
• Composition
• Inheritance
– Only protocol that needs to be
studied is that of container.
– Requires us to look at the
parent’s as well as child’s
protocol.
– Requires us to explicitly send
messages to the inner object.
– Reuses the parent’s code with no
explicit references.
– Restricts operations on inner
object to those needed.
– Allows all the parent operations
to be applied, even those that are
meaningless for the child.
– Creates an independent type.
– Allows us to use the child
anywhere the parent can be used
– Makes use of composition an
easily changed detail.
– Ties the child to choice of the
parent structure.
7/16/2015
© Charles E. Hughes 2000
76
Case Study: Sets and Lists
List protocol
addFirst: anElement
firstElement
length
includes: anElement
remove: anElement
Set protocol
add: anElement
size
includes: anElement
remove: anElement
Set is-a List (inheritance from List)
add: anElement
(self includes: anElement)
ifFalse: [self addFirst: anElement]
size
^self length
Set has-a List (composition)
add: anElement
(self includes: anElement)
ifFalse: [list addFirst: anElement]
size
^list length
includes: anElement
^list includes: anElement
remove: anElement
list remove: anElement
A scary aside: what if two threads performed simultaneous operations on same set?
7/16/2015
© Charles E. Hughes 2000
77
Comparing Set Implementations
•
•
Composition is simple in that protocol is tailored to Set.
In contrast, inheritance requires us to look at List’s and Set’s protocols.
•
Inheritance is lighter weight; it reuses List’s code with no explicit
references.
In contrast, composition requires explicit messages to List.
•
•
•
Composition restricts operations on Set to those that are applicable.
In contrast, inheritance allows all List operations to be applied, even
those that are meaningless for Sets.
•
•
Inheritance allows us to use Sets anywhere Lists can be used.
In contrast, composition creates an independent type.
•
Composition makes use of List structure an implementation detail that
can easily be changed.
In contrast, inheritance ties Set to choice of List structure.
•
7/16/2015
© Charles E. Hughes 2000
78
Replacement vs Refinement
• Replacement – overriding a method in parent class – can break
subtype relationship.
• Refinement – adding a prologue and/or epilogue to parent
method – can mitigate the interference with subtyping.
• In Smalltalk and Java we can use parent method by sending a
message to super, our parent.
Example:
“Initializing a DisplayTextView”
initialize
super initialize. “View’s initialize does most of work”
centered  false “Specific to Text”
7/16/2015
© Charles E. Hughes 2000
79
Pros and Cons of Inheritance
•
•
Plus
– Reusability (design and code)
– Protocol Consistency (e.g., in
Collections and Components)
– Software ICs
– Frameworks (e.g., MVC, awt)
– Lightweight Methods
7/16/2015
– Speed (generally overrated)
• premature optimization is deadly
– Size (if must carry many base
classes)
– Message passing overhead
(higher in untyped languages)
– Rapid Prototyping
– Information Hiding
Minus
– Complexity (yo-yo problem)
– Restricted control over
foundation classes
© Charles E. Hughes 2000
80
Common Types of Inheritance
• Specialization
• Specification
• Construction
• Generalization
• Extension
• Limitation
• Variance
• Combination
7/16/2015
© Charles E. Hughes 2000
81
Inheritance -- Specialization
• Extends protocol of superclass to create a more
specialized object
– Adds new behaviors
– New class is a subtype of parent
7/16/2015
© Charles E. Hughes 2000
82
Inheritance -- Specification
• Implements portions of protocol of superclass
– Superclass is abstract; new class realizes its specifications
– + in Float specifies the abstract + of Number
7/16/2015
© Charles E. Hughes 2000
83
Inheritance -- Construction
Somewhat evil
• Uses functionality of superclass, but is not a subtype
– Breaks principle of substitutability
– Stack can be constructed from a Vector
– Very often, children and parents do not have same interface
– Often used for quick and dirty prototyping
– Often is result of confusion of has-a with is-a
7/16/2015
© Charles E. Hughes 2000
84
Inheritance -- Generalization
• Extends superclass to create a more general object
– Extends parts/functionality
– ColorForm adds a color map with transparency to Form
– Overrides displayOnPort:at: to paint with transparencies
– Often occurs when design based on state, not behaviors
– Often sign of inverted hierarchy
7/16/2015
© Charles E. Hughes 2000
85
Inheritance -- Extension
• Extends superclass to add completely new
functionality
– Adds functionality not tied to parent
– In ST-80, asLowercase in String extends ArrayedCollection
– In Java Applet extends Component
7/16/2015
© Charles E. Hughes 2000
86
Inheritance -- Limitation
Definitely evil
Restricts superclass protocol
Limits functionality – breaks subtyping
In ST-80, Symbol inherits from String but disallows access to its
characters
“Here’s the evil code”
at: anInteger put: anObject
"You cannot modify the receiver."
self errorNoModification
7/16/2015
© Charles E. Hughes 2000
87
Inheritance -- Variance
Two unrelated (by is-a) classes have similar implementations
There is no subtyping, just common code
A Button is not a Model, but it does have dependents
Model provides fast dependent notification
Parent-child choice is arbitrary
Generally reflects need for an abstract parent of both
7/16/2015
© Charles E. Hughes 2000
88
Inheritance -- Combination
Combines features of two or more parents
Requires multiple inheritance to do properly
Java’s Interface is a way to achieve this
7/16/2015
© Charles E. Hughes 2000
89
Abstract versus Concrete
• Abstract
– Define protocols by providing a mix of implemented and abstract
(virtual) features.
– They are internal nodes in hierarchy.
– Abstract become more concrete as you traverse down the hierarchy.
• Concrete
– Provide templates for instances.
– They are leaf nodes in hierarchy.
– All features are implemented
• Prototype versus Mature
– In rapid prototyping we often inherit from concrete.
– As code matures, the Abstract/Concrete distinction becomes clearer.
• The job of an abstract class is to meet the needs of its heirs.
• The job of a concrete class is to meet the needs of its clients.
7/16/2015
© Charles E. Hughes 2000
90
Java’s Abstract Number Class
public abstract class Number implements java.io.Serializable {
public abstract int intValue();
public abstract long longValue();
public abstract float floatValue();
public abstract double doubleValue();
public byte byteValue() { // can implement using intvalue()
return (byte)intValue();
}
public short shortValue() { // can implement using intvalue()
return (short)intValue();
}
}
7/16/2015
© Charles E. Hughes 2000
91
Java’s Concrete Integer Class
public class Integer extends Number { // it’s exposed for use
private int value; // private means that it’s not known outside here
public Integer(int value) { // used to construct new Integer objects
this.value = value;
}
public int intValue() { // it’s exposed for use
return value;
}
… …
}
// using Integer
Integer myInt = new Integer(7); // can use constructor since it’s
public
int myIntVal = myInt.intValue(); // can use intValue() since it’s public
int myIntVal = myInt.value; // ILLEGAL since value is private
7/16/2015
© Charles E. Hughes 2000
92
Heirs versus Clients
• Heirs inherit features from class (superclasses)
– Protection from heirs is often weak
• Smalltalk totally exposes class to heirs
• Java offers private vs protected vs package vs public, also final
– Superclass can use subclassResponsibility / abstract to specify
protocol without implementation
• Clients create and use instances of a class
– Only see protocol / not state
• Communication is purely through messages
7/16/2015
© Charles E. Hughes 2000
93
Wisdom on Class Hierarchies
• Class hierarchy should be deep and narrow
– Get most features through inheritance, not construction.
– Add one major capability per class.
– Migrate features as high as possible.
– Extend, never suppress during inheritance.
• An Unhealthy Hierarchy
– Failure to specialize can destroy is-a hierarchy and thus create
instances that are not properly described by superclass protocol.
– A hovercraft is not an aircraft according to subtyping.
– What if a user of this hierarchy relies on protocol and sends a
collection of aircraft messages to fly over the Grand Canyon!?
7/16/2015
© Charles E. Hughes 2000
94
Multiple versus Single
• Single – you only get one immediate ancestor.
Commonly there is an “Eve” class called Object.
• Multiple – you can have many parents (even more than
two). This may or may not come with a root class.
• Repeated – that’s when the same class is your
ancestor from two different lineages. This can only
come as a special case of multiple.
7/16/2015
© Charles E. Hughes 2000
95
Hierarchy – simulation protocol
SimObject
AbstractPlayer
AbstractGhost
Vehicle
GhostVehicle
• Hierarchy separates Players from Ghosts because their
simulation protocols differ.
• BUT, a vehicle player and vehicle ghost are very similar. We
could just as well have abstracted on real world rather than
simulation behavior.
7/16/2015
© Charles E. Hughes 2000
96
Multiple Inheritance Solution
SimObject
AbstractPlayer
AbstractVehicle
Vehicle
AbstractGhost
GhostVehicle
• One provides supports Player/Ghost simulation protocols.
• Other supports object characteristics that are independent of
whether it’s a ghost (stand-in for object) or player (the real object;
it maintains ground truth for this object and all its distributed
copies).
7/16/2015
© Charles E. Hughes 2000
97
Java’s Choice
• Single inheritance, but with multiple interfaces.
• C++ allows many parents, and supports repeated
inheritance.
• Historically, Smalltalk supported multiple inheritance,
BUT kept it under the hood by not supporting its
creation in the browser (IDE).
7/16/2015
© Charles E. Hughes 2000
98
Java’s Compromise
• Java does not support true multiple inheritance
– does support the “interface” construct
– You get the method signatures from the interface, but you must
implement all of the methods
interface dummy {
void method1();
}
class realOne implements dummy {
void method1() {
//something cool
}
}
• So why use interfaces?
– Nice place to store constants
– Make sure your object conforms to a standard interface
• Useful for composibility of components
– Works with type checking system
– Can use as a “marker” – Cloneable, Serializable, …
7/16/2015
© Charles E. Hughes 2000
99
Objectionable Reimbursement
An object-based solution
Full code is linked from home page
7/16/2015
© Charles E. Hughes 2000
100
Objectionable Reimbursement
package objectionable.reimbursement1;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
import java.util.Hashtable;
// This solution is really object-based.
// We want/need an object-oriented solution.
// However, prototypes help us understand our needs.
public class ProcessBasedReimbursement extends JApplet {
Hashtable procedures = new Hashtable();
…
}
class Procedure {
…
}
7/16/2015
© Charles E. Hughes 2000
101
Procedure Class – struct-like
// This is a weak class -- more of a struct
class Procedure {
static final String[] strategies =
{"Fixed Payout","Percentage Actual Cost","Loss Limit"};
static final int Fixed = 0;
static final int PercentActual = 1;
static final int LossLimit = 2;
String code;
String name;
int strategy;
int limit;
int percentage;
Procedure(String code, String name, int strategy,
int limit, int percentage) {
this.code = code;
this.name = name;
this.strategy = strategy;
this.limit = limit;
this.percentage = percentage;
}
}
7/16/2015
© Charles E. Hughes 2000
102
Widgets and Listeners
newCodeLabel.setText("Code");
codeField.setPreferredSize(new Dimension(100, 21));
descriptionLabel.setPreferredSize(new Dimension(96, 17));
descriptionLabel.setToolTipText("");
descriptionLabel.setText("Procedure Name");
nameField.setPreferredSize(new Dimension(100, 21));
strategyLabel.setText("Strategy");
limitLabel.setText("Payment Limit");
limitField.setPreferredSize(new Dimension(100, 21));
percentLabel.setText("Percentage");
percentField.setPreferredSize(new Dimension(100, 21));
strategySelect.setPreferredSize(new Dimension(100, 21));
newProcButton.setBorder(BorderFactory.createRaisedBevelBorder());
newProcButton.setActionCommand("ADD PROCEDURE");
newProcButton.setText("ADD PROCEDURE");
newProcButton.addActionListener(
new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
newProcButton_actionPerformed(e);
}
}
);
7/16/2015
© Charles E. Hughes 2000
103
newProcButton
Listener’s Action
void newProcButton_actionPerformed(ActionEvent e) {
String code=codeField.getText();
if(code.equals("")) return;
int limit = 0;
if(!limitField.getText().trim().equals(""))
try {
limit = Integer.parseInt(limitField.getText());
if(limit<0) throw new Exception("Less Than Zero");
} catch(Exception e1) {
JOptionPane.showMessageDialog(this,
"Limit Value Must be a Non-Negative Integer");
return;
}
int percentage = 0;
… // followed by tests like above
procedures.put(code.toUpperCase(),
new Procedure(code, nameField.getText(),
strategySelect.getSelectedIndex(), limit, percentage)
);
}
7/16/2015
© Charles E. Hughes 2000
104
clearProcButton
Listener’s Action
void clearProcButton_actionPerformed(ActionEvent e) {
codeField.setText("");
nameField.setText("");
strategySelect.setSelectedIndex(0);
limitField.setText("");
percentField.setText("");
}
7/16/2015
© Charles E. Hughes 2000
105
Exercise #2
• Continue Exercise #1 in light of Classroom
Discussions
7/16/2015
© Charles E. Hughes 2000
106
Day#5
7/16/2015
© Charles E. Hughes 2000
107
Discussion of Reimbursement1
•
Does this meet requirements?
•
Two new classes with has-a relationship actually composition
– Procedure is a data structure in service to ProcessBasedReimbursement
– An OO design tends to have cooperating not subservient objects
•
What does it take to extend this design to include deductible?
•
Is this even a good non-OO solution?
– Can be data driven, even if not OO
– Such an approach can foster good algorithmic reuse
•
Programming in the small does not allow us to make a hard “bad”
versus “good” comparison
– We will just focus on solution space versus problem space orientation
7/16/2015
© Charles E. Hughes 2000
108
An OO Reimbursement Design
• Abstract class PaymentStrategy. Includes method
abstract public int reimburse(int payment);
• Children are:
– FixedPaymentStrategy
– PercentagePaymentStrategy
– LossLimitPaymentStrategy
• Children implement reimburse( ) and must have appropriate
constructors and state variables. Note,
LossLimitPaymentStrategy can use PercentagePaymentStrategy
7/16/2015
© Charles E. Hughes 2000
109
Problems with OO Reimburse
• First solution can expand list of strategies for combo box easily –
adding code or new filters is the pain.
• OO code can easily add new strategies, but how does combo box
know what the strategies are?
– This was easy in previous solution with single class array that
contained names of strategies
– A solution is that each class can have initialization code that is
automatically run when the class is loaded. Abstract class can allow
heirs to register their names, and thus can provide combo box with
list of strategies.
– The above still requires a mechanism to call the right constructor,
given only the name of the class as a String.
7/16/2015
© Charles E. Hughes 2000
110
Language Influences Design
• The world is not perfect, with the choice of language
irrelevant like we academics pretend it to be.
• In Java, Class is an class that allows you to recast the
name of a class as the corresponding class.
• To make it work for us we also need to be able to send
messages to class objects (classes must be objects
as well as the creators of objects).
• The relevant message for our purposes is
newInstance()
7/16/2015
© Charles E. Hughes 2000
111
Classes as Objects
• In C++ classes are not first class objects.
• In Smalltalk a class is a first class object and this is
reflected by the fact new is a message to a class
object.
• Java is a bit ambivalent.
– The name of a class is not a reference to the class object, so
new is not a message, but is rather a keyword.
– You can get the class object for class MyClass by
Class c = Class.forName(“MyClass”); //get class object
MyClass m = c.newInstance(); // instantiate
7/16/2015
© Charles E. Hughes 2000
112
Design Assignment #1
•
This is a graded assignment due at the start of class on
Tuesday, September 12.
•
Provide an OO design of a medical reimbursement program
which categorizes procedures as follows?
–
Fixed (e.g., up to $25 for procedure 22)
–
Percentage (e.g., 75% of charge for surgical procedure 103)
–
Stop-loss (e.g., 50% of charge up to a max of $750)
–
Three more (each of above, but with a deductible)
•
Associate each procedure code with a reimbursement strategy.
•
Note: this is not a programming assignment. That comes next
week.
7/16/2015
© Charles E. Hughes 2000
113
Common Java Interfaces
7/16/2015
© Charles E. Hughes 2000
114
Common Java Interfaces#1
Collection: must implement
int size();
boolean isEmpty();
boolean add(Object o);
boolean remove(Object o);
boolean contains(Object o);
Iterator iterator();
Object[ ] toArray();
Object[ ] toArray(Object a[ ]);
boolean containsAll(Collection c);
boolean addAll(Collection c);
boolean removeAll(Collection c);
boolean retainAll(Collection c);
7/16/2015
© Charles E. Hughes 2000
115
Abstract Collection (partial)
class AbstractCollection implements Collection {
public abstract int size( );
public abstract Iterator iterator( );
public abstract boolean add(Object o); // note semantics are unknown
public boolean isEmpty( ) { return size( ) == 0; }
public boolean remove(Object o);
Iterator e = iterator();
if (o==null) while (e.hasNext()) if (e.next()==null) { e.remove(); return true; }
else while (e.hasNext()) if (o.equals(e.next())) { e.remove(); return true; }
return false;
}
public boolean removeAll(Collection c) {
boolean modified = false;
Iterator e = iterator();
while (e.hasNext()) if(c.contains(e.next())) {e.remove(); modified = true;}
return modified;
}
…
}
7/16/2015
© Charles E. Hughes 2000
116
toString() Collection Method
public String toString() {
StringBuffer buf = new StringBuffer();
Iterator e = iterator();
buf.append("[");
int maxIndex = size() - 1;
for (int i = 0; i <= maxIndex; i++) {
buf.append(String.valueOf(e.next()));
if (i < maxIndex)
buf.append(", ");
}
buf.append("]");
return buf.toString();
}
7/16/2015
© Charles E. Hughes 2000
117
Common Java Interfaces#2
Runnable : must implement
void run()
Iterator: must implement
boolean hasNext();
Object next();
void remove();
ActionListener extends EventListener: must implement
void actionPerformed(ActionEvent e);
MouseListener extends EventListener: must implement
void mouseClicked(MouseEvent e);
public void mousePressed(MouseEvent e);
public void mouseReleased(MouseEvent e);
public void mouseEntered(MouseEvent e);
public void mouseExited(MouseEvent e);
void clear();
int hashCode();
7/16/2015
© Charles E. Hughes 2000
118
Abstract MouseAdapter
public abstract class MouseAdapter implements MouseListener {
// this implements all services, but is declared abstract
// it exists for its heirs; can have no clients
// Invoked when the mouse has been clicked on a component.
public void mouseClicked(MouseEvent e) { }
// Invoked when a mouse button has been pressed on a component.
public void mousePressed(MouseEvent e) { }
// Invoked when a mouse button has been released on a component.
public void mouseReleased(MouseEvent e) { }
// Invoked when the mouse enters a component.
public void mouseEntered(MouseEvent e) { }
// Invoked when the mouse exits a component.
public void mouseExited(MouseEvent e) { }
}
7/16/2015
© Charles E. Hughes 2000
119
Vectors and Iterators
import java.util.*;
public class VectorApp {
//Main method
public static void main(String[ ] args) {
Vector v = new Vector(3);
v.add(new Integer(5));
v.add(new Integer(2));
v.add(new Integer(7));
v.add(new Integer(6));
v.add(new Integer(14));
Iterator itr = v.iterator();
while (itr.hasNext())
// Note cast (Integer) since iterators return Object
System.out.println(((Integer) itr.next()).toString());
}
}
7/16/2015
© Charles E. Hughes 2000
120
Vectors and Iterators
import java.util.*;
public class VectorApp {
//Main method
public static void main(String[ ] args) {
Vector v = new Vector(3);
Vector w = new Vector();
w.add(new Integer(-22));
v.add(new Integer(5));
v.add(new String("Hello"));
v.add(w);
v.add(new Integer(6));
v.add(new Float(1.4));
Iterator itr = v.iterator();
while (itr.hasNext())
System.out.println(itr.next().toString());
}
}
7/16/2015
© Charles E. Hughes 2000
121
First Exposure to Java Model
JComboBox strategySelect = new
JComboBox(Procedure.strategies);
Invokes constructor
public JComboBox(final Object items[ ]) {
super();
setModel(new DefaultComboBoxModel(items));
init();
}
7/16/2015
© Charles E. Hughes 2000
122
DefaultComboBoxModel
public class DefaultComboBoxModel extends AbstractListModel;
public abstract class AbstractListModel implements ListModel;
public interface ListModel {
int getSize();
Object getElementAt(int index);
void addListDataListener(ListDataListener l);
void removeListDataListener(ListDataListener l);
}
The key is that a list model must implement methods that allow its view to
find out the length of the list and the current values of the items in the list.
Like all models a list model must also allow list data listeners to add and
remove themselves from its listener list.
7/16/2015
© Charles E. Hughes 2000
123
JComboBox setModel Method
public void setModel(ComboBoxModel aModel) {
ComboBoxModel oldModel = dataModel;
if ( dataModel != null )
dataModel.removeListDataListener(this);
dataModel = aModel;
firePropertyChange( "model", oldModel, dataModel);
dataModel.addListDataListener(this);
invalidate();
}
7/16/2015
© Charles E. Hughes 2000
124
Day#6
7/16/2015
© Charles E. Hughes 2000
125
Programming Assignment #1
•
•
This is a graded assignment due at the start of class on
Thursday, September 28.
Develop a medical reimbursement program which categorizes
procedures as in your previous design assignment.
–
–
•
•
This is the programming assignment. It needs to be an OO program
written in Java.
See my “solution” as a starting point
Turn in (electronically) a zip or jar file that I can unzip and run. I
prefer that it be a JBuilder project. Be sure that all parts are
present and that you generate the classes in one of your
subdirectories, not somewhere else on disk. This should also
contain the description (see below).
Turn in (on paper and in zip file) a description of your hierarchy
and a critique – what feels good; what feels bad?
7/16/2015
© Charles E. Hughes 2000
126
Reimbursement Strategy
package acceptable.reimbursement;
import java.util.*;
abstract public class ReimbursementStrategy {
// Each child adds its name here so all strategies are discovered
static Vector strategies = new Vector();
String code;
String name;
int limit;
int percentage;
static void addStrategy(String strategy) {
strategies.add(strategy);
}
7/16/2015
© Charles E. Hughes 2000
127
Reimbursement Strategy #2
// Oooh. This bothers me. Think about why.
void init(String code, String name, int limit, int percentage) {
this.code = code;
this.name = name;
this.limit = limit;
this.percentage = percentage;
}
// Useful for seeing contents of entries
public String toString() {
return
"Code="+code+";name="+name+";limit="+limit+";percent="+perc
entage;
}
// Concrete strategies must override
abstract int reimburse(int payment);
}
7/16/2015
© Charles E. Hughes 2000
128
Fixed Payment Strategy
package acceptable.reimbursement;
public class FixedPaymentStrategy extends
ReimbursementStrategy {
// Payment is bound by actual expenditure
int reimburse(int payment) {
return Math.min(payment, limit);
}
// Cool. This is how we know about all strategies
// Hmm. Could this be done better by parent. Think about it.
static { strategies.add("FixedPaymentStrategy"); }
// Useful for debugging
public String toString() {
return "FixedPaymentStrategy:"+super.toString();
}
}
7/16/2015
© Charles E. Hughes 2000
129
Model Notation
7/16/2015
© Charles E. Hughes 2000
130
UML – Static Aspects
• Notations for
– Classes , Interfaces, Objects
– Inheritance (usually open arrow directed toward parent)
– Implementation (like inheritance, except dotted line)
– Association (annotations line)
• Aggregation (open diamond facing container)
• Composition (closed diamond facing container)
Open arrowheads and diamonds are a pain in PowerPoint
7/16/2015
© Charles E. Hughes 2000
131
Observer Pattern Classes
Subject
+Attach(Observer : Observer) : void
+Detach(Observer : Observer) : void
+Notify() : void
for all o in observers
{
o->Update();
}
Observer
+Update()
ConcreteSubject
ConcreteObserver
-subjectState : state
+GetState() : state
+setState(state : state) : void
-observerState : state
+Update()
observerState = subject->GetState()
return subjectState
7/16/2015
© Charles E. Hughes 2000
132
Sequence Diagrams
• Shows time order of events
– Objects head columns (initiators on left)
– Time sequence is top to bottom
– Directed connector is labeled with method call
• Often associated with scenarios
7/16/2015
© Charles E. Hughes 2000
133
Observer Pattern Sequence
Time
aConcreteSubject
aConcreteObserver
anotherConcreteObserver
setState()
Notify()
Update()
GetState()
Update()
GetState()
7/16/2015
© Charles E. Hughes 2000
134
Statecharts
• Generalized Finite State Machines
• Transitions are associated with events and conditions
• States indicate internal state of object
• Hyperstates are composed FSMs; used to control
complexity or represent level of granularity
7/16/2015
© Charles E. Hughes 2000
135
The Java Environment
7/16/2015
© Charles E. Hughes 2000
136
Java Attributes
• Run on many platforms
– Unix, Windows, Mac
• Develop on multiple platforms
– The usual suspects
• Reuse at many levels
– Components
– Classes (families of components)
– Frameworks (collaborating components)
7/16/2015
© Charles E. Hughes 2000
137
Features
• Browser friendly
• Network aware
• Implements new paradigms
– User interface framework
– Distributed computing framework(s)
– Multimedia framework
– 3D framework
– …
7/16/2015
© Charles E. Hughes 2000
138
Protecting Your Investment
• Reuse, don’t reinvent
• Use components and frameworks
– Across many products
– Component assembly via beans
• Plug in look and feel
– Maintain same across all platforms
– Or adapt to local preferences
7/16/2015
© Charles E. Hughes 2000
139
More on Your Investment
• Develop for international market
– Java characters are Unicode
• Meet accessibility needs of clientele
– Visual or hearing impaired
• Deliver early prototypes
– Open/closed principle of good OO
• Upgrade incrementally
– Replace parts of system through jars
7/16/2015
© Charles E. Hughes 2000
140
How is Java Portable?
• Java source code (.java) is compiled for a JVM
– JVM = Java virtual machine
• Byte code files (.class) run on the JVM via
– Machine emulation on local host
– Just-in-time compilation from byte to native codes
– An actual silicon implementation of the JVM
7/16/2015
© Charles E. Hughes 2000
141
JVM
• RISC architecture
• Registers used to maintain stack
– Top of stack, Local variables, Frame (current context)
• Primitive data and object handles are on stack
• Objects are allocated from a garbage collected heap
• JVM also does
– Exception handling and thread synchronization
7/16/2015
© Charles E. Hughes 2000
142
The Development Environment
• You can use the JDK 1.2.2 or 1.3 (Beta) which provides
the compiler and JVM.
• There are lots of IDEs.
• My choice of Borland JBuilder3 was its lack of placing
tags in your source to synchronize the Visual Design
component with your code. It also has a great help
facility and instant access to base class code.
• JBuilder3 uses the JVM for its compiler and run time,
but does incremental parsing to keep your source
synched with design.
7/16/2015
© Charles E. Hughes 2000
143
Applications versus Applets
• Java applications run like any other program, with all the rights
and privileges thereto appertaining
• Applets run in a sandbox, Internet browser or applet viewer
– The sand box provides services, but limits what applet can do
• No reading or writing files on local machine (just from host)
• No network connections, except back to host
• No inter-applet communication except to others from same host
• JVM enforces byte-code verification, security management
• Java language does not allow pointer manipulation
7/16/2015
© Charles E. Hughes 2000
144
Hello Examples
7/16/2015
© Charles E. Hughes 2000
145
Hello Java Application
class Hello {
/** A Java app prints "Hello!" */
public static void main (String args[]) {
System.out.println("Hello!");
/* System.out refers to the standard output */
}
}
7/16/2015
© Charles E. Hughes 2000
146
Vocabulary
• public
– accessible by clients of class
• static
– belongs to the class; non-static belong to instances
• void
– returns nothing
• main
– must be public; called by you execute application
• String
– immutable strings (StringBuffer used if must change characters)
• String args[]
– array of Strings from command line (does not include class name)
• System
– base class containing system items like console handles
• System.out
– console output stream
7/16/2015
© Charles E. Hughes 2000
147
A Swing Java Application
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class HelloApp extends JFrame {
public HelloApp() {
super("An Application");
Container contentPane = getContentPane();
Icon icon = new ImageIcon("swing.gif", "Duke on a swing");
JLabel label = new JLabel("Welcome!", icon,
SwingConstants.CENTER);
contentPane.add(label, BorderLayout.CENTER);
}
public static void main(String args[]) {
final JFrame f = new HelloApp();
f.setBounds(100,100,300,250);
f.setVisible(true);
f.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
f.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {System.exit(0);}
});
}
} 7/16/2015
© Charles E. Hughes 2000
148
Vocabulary
•
•
•
•
•
•
•
•
•
import
– opens up a library so we can use its classes
javax.swing.*; java.awt.*; java.awt.event.*
– all classes defined in directories <classpath>/javax/swing/, etc.
– swing is new model/view framework
JFrame
– a heavyweight container
getContentPane
– called to get the Container into which “lightweight” Swing components are
placed
ImageIcon
– class each of whose instances holds a named small image
JLabel
– swing label that includes text and a graphical component; awt labels contain
only text
final
– write once variable
addWindowListener
– listeners gets notified of events in which they are interested
new WindowAdapter() { overriden methods }
– anonymous object to capture window events; here exit on close of window
7/16/2015
© Charles E. Hughes 2000
149
Hello Java Applet
import java.awt.*;
import java.applet.Applet;
public class HelloApplet extends Applet {
public void paint(Graphics g) {
Dimension d = getSize();
g.setColor(Color.black);
g.fillRect(0,0,d.width,d.height);
g.setFont(new Font("Helvetica", Font.BOLD, 24));
g.setColor(new Color(255, 215, 0)); // gold color
g.drawString("Welcome!", 40, 25);
g.drawImage(getImage(getCodeBase(), "swing.gif"), 20, 60, this);
}
}
7/16/2015
© Charles E. Hughes 2000
150
Vocabulary
• java.applet.Applet
– Applet class defined in the directory <classpath>/java/applet/
• extends
– adds or overrides services from a parent class (super type)
• Applet
– the class defining standard applet services and parts
• paint
– called when Component image is originally drawn or must be
repaired (uses clipping)
• Graphics
– the class associated with graphical contexts
• Dimension
– class of two-dimensional objects
• getSize( )
– returns dimension of Applet
• getImage(getCodeBase(), "swing.gif")
– Applets can acquire images; code base is directory of Applet
7/16/2015
© Charles E. Hughes 2000
151
Hello Java Applet HTML
<title>Test</title>
<hr>
<applet code=“HelloApplet.class"
width=300 height=150>
</applet>
<hr>
7/16/2015
© Charles E. Hughes 2000
152
Hello Java JApplet
import javax.swing.*;
import java.awt.*;
public class HelloJApplet extends JApplet {
public void init() {
Container contentPane = getContentPane();
Icon icon = new ImageIcon("swing.gif", “Swinging Duke");
JLabel label = new JLabel("Welcome!", icon,
SwingConstants.CENTER);
contentPane.add(label, BorderLayout.CENTER);
}
}
7/16/2015
© Charles E. Hughes 2000
153
Vocabulary
• JApplet
– the class defining standard applet services and parts in the
swing framework
• getContentPane
– called to get the Container into which “lightweight” Swing
components are placed
• ImageIcon
– class each of whose instances holds a named small image
• SwingConstants
– interface holding standard Swing constants
• BorderLayout
– interface holding standard BorderLayout constants
7/16/2015
© Charles E. Hughes 2000
154
HTML Converter
• This garbage will hopefully end soon
• Until then, write standard Applet tags and then use
HTMLConverter or use Communicator 6
• HTMLConverter has a simple GUI and can be used to convert
whole trees (recursively down directories)
• It can tailor output to a specific browser or all standard browsers
• Don’t need this when running in appletviewer, Communicator 6,
HotJava, Forte, or JBuilder3
7/16/2015
© Charles E. Hughes 2000
155
Converted JApplet HTML
<OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"WIDTH = 300 HEIGHT = 150
codebase="http://java.sun.com/products/plugin/1.1.1/jinstall-111-win32.cab#Version=1,1,1,0">
<PARAM NAME = CODE VALUE = “HelloJApplet.class" >
<PARAM NAME = ARCHIVE VALUE = "HelloJApplet.jar" >
<PARAM NAME="type" VALUE="application/x-java-applet;version=1.1">
<COMMENT>
<EMBED type="application/x-java-applet;version=1.1" java_CODE = " HelloJApplet.class"
java_ARCHIVE = "HelloJApplet.jar" WIDTH = 300 HEIGHT = 150
pluginspage="http://java.sun.com/products/plugin/1.1.1/plugin-install.html">
<NOEMBED></COMMENT>
</NOEMBED></EMBED>
</OBJECT>
<!-<APPLET CODE=" HelloJApplet.class" ARCHIVE="HelloJApplet.jar" WIDTH=300 HEIGHT=150 >
</APPLET>
-->
7/16/2015
© Charles E. Hughes 2000
156
Jars
• To transport images and multiple class files, put them
in a jar – can use deployment wizard in JBuilder3
<APPLET
CODE = “HelloJApplet.class"
ARCHIVE = "HelloJApplet.jar"
WIDTH = 300 HEIGHT = 150 >
</APPLET>
7/16/2015
© Charles E. Hughes 2000
157
Get Some Experience
• For those of you who have never written in Java
before, alter the trivial HelloJApplet applet to make it
personal. Put in any image you like and any text.
• For those with experience, help your colleagues get
started.
7/16/2015
© Charles E. Hughes 2000
158
Day#7
7/16/2015
© Charles E. Hughes 2000
159
The Java Language / Culture
7/16/2015
© Charles E. Hughes 2000
160
Java versus C++
• Standard base classes
– Bare standards in template classes
• (Almost) pure object-oriented
– C security blanket is always there
• Is designed with Internet in mind
– Can be coerced to work on net
• Enforces security policies
– Supports (encourages) anarchy
7/16/2015
© Charles E. Hughes 2000
161
More Java versus C++
• Manages memory to avoid leaks
– You control all memory management
• Detects exceptions
Requires handling by program
– Has some rudimentary facilities
• Cleanly supports concurrency
– Provides some procedural support
• Supports network & distributed computing
– Libraries exist for this – but no one standard
7/16/2015
© Charles E. Hughes 2000
162
Core of Java is C
• BUT, Java is almost pure OO.
• Its one exception is its support for primitive types
– boolean
wrapper Boolean
– byte, short, int, long
wrappers Byte,Short,Integer,Long
– char
wrapper Character
– float, double
wrappers Float,Double
• But all arrays are objects (array is fixed size with
attribute length, a.length is number of items)
7/16/2015
© Charles E. Hughes 2000
163
Wrappers
• Primitives can be wrapped in an object so they can
participate as first class citizens of the object world
• This is necessary for instance if an int is to be placed
in a Vector (an expandable array of objects)
• Wrappers offer lots of other class services
Integer.parseInt(String)
Float.isNan(float)
Double.isInfinite(double)
Constants such a
public static final Boolean.TRUE = new Boolean(true)
7/16/2015
© Charles E. Hughes 2000
164
Java Strings
• Two kinds String (cannot manipulate contents) and
StringBuffer (is completely mutable)
• Operators + and += overloaded to mean concatenation
• Strings are created by class constructor
String s = String();
or just writing a string literal
String s = “Hello”;
• A String is not an array of characters (well, under the
covers may be), so s.length() is okay, but s.length is
not
7/16/2015
© Charles E. Hughes 2000
165
StringTokenizer
• The StringTokenizer class can be used to parse a
string into its component words
import java.io.*;
import java.utils.*;
public class EchoWords {
public static void main(String[ ] args) throws IOException {
BufferedReader keyBoard = new BufferedReader(
new InputStreamReader(System.in));
String line;
while ((line = keyBoard.readLine()) != null) {
StringTokenizer tokens = new StringTokenizer(line);
while (tokens.hasMoreTokens())
System.out.println(“==> “ + tokens.nextToken());
}
}
7/16/2015
© Charles E. Hughes 2000
166
Some non-C++ Characteristics
• All non-static methods are polymorphic (dynamically bound –
virtual in C++)
• There are no global variables (but static variables are long-lived)
• All methods are associated with classes – no standalone
functions as in C++
• No multiple inheritance – interfaces instead
• No goto
• 16-bit Unicode, not 8 bit characters
• Exception handling, multiple threads and dynamic garbage
collection are in Java’s core
7/16/2015
© Charles E. Hughes 2000
167
A Really Big Difference
• Variables that refer to primitive types hold values of
that type
• Variables that refer to objects, even arrays which are
always objects, are reference variables – they hold
references, not values
• A reference can never be manipulated – you can use it
to access or change what it refers to, but never it
• From above, we can ascertain that Java does not
support pointer arithmetic – Thank you Sun
7/16/2015
© Charles E. Hughes 2000
168
More about References
• In C++ you can cast a pointer to any type
• You can only use cast for narrowing in Java
• In C++ you manage the return of space to the heap
• In Java reference variables point to objects in a
garbage collected heap – when an object loses all
references, its space can be reclaimed
• GC is great, but it can and has been a performance
issue in Java – Hot Spot JVM is great improvement
7/16/2015
© Charles E. Hughes 2000
169
Defaults
• Reference variables have a default value of null – the
empty reference
• Primitive types have default values of their zeros
(false for boolean)
7/16/2015
© Charles E. Hughes 2000
170
Arithmetic
• Integers do not overflow or underflow, they wrap
• Integer divide (/) and mod (%) can throw an
ArithmeticException if second operand is a 0
• Floating point numbers are closed under all
operations (IEEE-754-1985)
• Float closure is accomplished by values  and NaN
(not a number). E.g., 0.0/0.0 is NaN
7/16/2015
© Charles E. Hughes 2000
171
Operator Overloading
• Outside of arithmetic, there is only one case of
operator overloading in Java, and the programmer has
not control of this
• The + operator is concatenation when Strings are
involved – identity (==) is not overloaded for Strings
7/16/2015
© Charles E. Hughes 2000
172
The Equality Issue
• In Java, the == operator means is the same object.
This is often called the identity operator
• In the case of primitives this gives you what you
expect, but not so for objects, including Strings
• To compare the values of the objects referenced by
two reference variables, you use the equals(obj)
service or the compareTo(obj) service, if it’s available
• compareTo(obj) is available for all objects whose
class implements the Comparable interface
7/16/2015
© Charles E. Hughes 2000
173
More on Comparison
• The equals(obj) operator must be redefined by each
class (or inherited from a compatible superclass). If
not done, then a class gets its implementation from
the Object class in which equality is identity
public boolean equals(Object obj) {
return (this == obj); }
• The o1.compareTo(o2) service must return an int
0 if o1.equals(o2)
<0 if o1 is less than o2
>0 if o1 is greater than o2
7/16/2015
© Charles E. Hughes 2000
174
Semantic Consistency
• If you define equals, it must be the case that
– if o1 == o2 then o1.equals(o2)
– If o1.equals(o2) then o1.hashcode() == o2.hashcode()
• If you clone an object (implement the Cloneable interface and
provide a clone() service) then
– (o.clone() != o) && (o.clone().equals(o))
• Thus, if a clone is shallow then the equals must also be shallow.
Note: the default clone() just creates a new instance with all its
fields the same as the original. This is a shallow copy
7/16/2015
© Charles E. Hughes 2000
175
Type Conversion
• A type denotes the set of all legal values of that type
• Type Compatibility
Type T1 is compatible with type T2 if a value of type T1 can appear
whenever a value of type T2 is expected and vice versa
• Type conversion comes in two forms
widening converts a type of a smaller to a type of a larger range
e.g., int to long or short to double
narrowing converts a type of a larger to a type of a smaller range
e.g., float to int or double to float
7/16/2015
© Charles E. Hughes 2000
176
Allowable Conversion
• Widening is carried out implicitly – you need say
nothing
float f = 10;
• Narrowing requires explicit casts. Even so, overflow
can occur, but that’s your problem
int j = (int) 37.7;
7/16/2015
© Charles E. Hughes 2000
177
A Brief Comment on Arrays
• Arrays are objects; a 2d array is an object that refers to a list of
references to objects, each of which is a row of the array
• The following do not allocate space for an array
– int[ ] age; // my preference – the type is ref to array of int
– float weight[ ]; // acceptable, but I don’t like it
• These declare references and allocate arrays
– int[ ] age = {62, 44, 52, 32, 7}; // array with five elements
– float[ ] weight = new float[10]; // indexed 0,…,9 (weight.length==10)
• In Java array referenced are always checked; not so in C++
7/16/2015
© Charles E. Hughes 2000
178
Creating Classes
public class Cat extends Feline
implements domesticate, purr {
private boolean houseTrained;
String owner; // package accessible by default
String vet;
boolean public isTrained() { … }
void startPurring() { … } // contractual from interface
void stopPurring() { … } // contractual from interface
String getVetName() { … } // contractual from interface
}
7/16/2015
© Charles E. Hughes 2000
179
Accessibility Attributes
Public
Protected
Package
Private
Class itself
Yes
Yes
Yes
Yes
Package
classes
Yes
Yes
Yes
No
Subclasses
Yes
Yes
No
No
Unrelated
Yes
No
No
No
7/16/2015
© Charles E. Hughes 2000
180
Day#8
7/16/2015
© Charles E. Hughes 2000
181
Other Attributes – Part 1
• static – associated with class, shared by all instances.
A static method can access only static fields.
• final – a final method cannot be overridden by children
a final variable is a constant (it must be initialized)
a final parameter to method is immutable
• abstract – declared but not fully defined; cannot
instantiate an abstract class
7/16/2015
© Charles E. Hughes 2000
182
Other Attributes – Part 2
• synchronized – a synchronized block of code is
atomic wrt others that synchronize on same object
• native – a native method is written in C or C++
• transient – a part of an object not included in the
system supported serialization; its persistency (if
required) is the responsibility of its class
• volatile – this is a mini version of synchronous; its
atomicity is of very fine granularity indeed
7/16/2015
© Charles E. Hughes 2000
183
Final versus C++ Const
• Final is very weak in comparison to const when it comes to
parameters
• It says that the value of the argument will not be changed
• BUT, if the argument is a reference, its copy can give you access
to the referenced object that is not affected by the final attribute
• NOTE: all arguments are passed by value in Java
That’s no big deal on reference – it’s a copy of the handle to the
corresponding object.
It is a bit restrictive on primitives; they must be wrapped in an
object to carry back changes in state
7/16/2015
© Charles E. Hughes 2000
184
Object Creation
Stack versus Heap
Automatic versus Dynamic
With automatic can have handles to nothing
Copy handle, but space is deleted
With both can have memory leaks
Failure to clean up when object destroyed
Handles (pointers) versus Object
Indirection can be explicit or implicit
Gets real interesting when have distributed objects
7/16/2015
© Charles E. Hughes 2000
185
Object Creation in Java/C++
• Constructors are the means to create objects in Java,
just like in C++
• Constructors are commonly overloaded
• If no constructor is supplied you get a no argument
one for free
• There is no underhand use of constructors for implicit
conversion, as seen in C++
7/16/2015
© Charles E. Hughes 2000
186
Rectangle Constructors
public class Rectangle {
private int length, width;
public Rectangle(int length, int width) {
// this means self – access to my parts that are shadowed
this.length = length; this.width = width;
}
public Rectangle(int side) {
this(side, side); // this means self – a constructor
}
public Rectangle() {
this(1, 1); // this means self – a constructor
}
…
}
7/16/2015
© Charles E. Hughes 2000
187
An Aside on Shadowing
• A local variable named x within a method shadows the
object’s part named x, if one exists
• Shadowing can be confusing or illuminating – it’s your
choice
• Shadowing can improve efficiency in multithreaded
apps by allowing you to copy the object state at top,
manipulate the similarly named copies within, and
then copy back the results at the end – only the
copying code needs to be synchronized
7/16/2015
© Charles E. Hughes 2000
188
More on Initialization
• Can initialize fields via initial values or an initialization
block
• Static (class, rather than instance) variables can be
initialized by a static block – one with static attribute
• An initialization block is recognizable by not being
part of any method
7/16/2015
© Charles E. Hughes 2000
189
Access to Parts and Services
• Access to the public parts and services provided by
an object are through the same dot qualifier notation
used in C++
• There is no equivalent to stuff like
*p.m();
p->m();
*(p++).v++
since Java has no explicit pointers
7/16/2015
© Charles E. Hughes 2000
190
Destructors
• Space allocated to unreferenced objects is
automatically garbage collected, so there is no
equivalent to C++ destructors
• There is a finalize() service that you can override (it’s
inherited from Object)
• finalize() is commonly used to ensure stability of file
systems and networks – flush and close connections
7/16/2015
© Charles E. Hughes 2000
191
Singleton Classes
• Most classes have public constructors, but that’s not
required or even desirable in all cases
• Consider a class like the Scheduler class in an
operating system. There should be just one instance
of the Scheduler class, created the first time it is
referenced.
• Can make the constructor private or, at least,
protected and have a getInstance() method which
returns the one and only instance
7/16/2015
© Charles E. Hughes 2000
192
Scheduler Class
public class Scheduler {
static public Scheduler getScheduler() {
if (scheduler == null)
scheduler = new Scheduler();
return scheduler;
}
protected Scheduler() {
// whatever
}
… // other services
private static Scheduler scheduler = null;
}
7/16/2015
© Charles E. Hughes 2000
193
Java’s Handling Singletons
• There are a number of singleton objects in Java, e.g.,
System which supplies needed standard streams in,
out and err .
• This could be done by a class that is instantiated just
once.
• It’s actually done by a class that is never instantiated.
It has a private constructor. All services are provided
as static. The parts are public static final.
private System() { }
public final static InputStream in = nullInputStream();
7/16/2015
© Charles E. Hughes 2000
194
Interfaces
• An interface is like a very abstract class
• It can only specify a contract – no method
implementations are allowed
• Interfaces can also declare and define static
constants, but not instance variables
• Interfaces cannot specify any static methods, and
their instance methods must all be public
– after all, this is a contract to clients
7/16/2015
© Charles E. Hughes 2000
195
Organizing Classes
• Classes are the building blocks, but they can become
very numerous and hard to manage
• Java provides two means for organizing classes
– the file and the package
• Classes in the same file are tightly coupled, with only
one allowed to be public – it’s name must match the
file name (class Charlie must be stored in Charlie.java)
• The more scalable organizing scheme is through
packages – classes bonded by mutual trust
7/16/2015
© Charles E. Hughes 2000
196
Inner Classes
• Classes can be embedded one deep
• An inner class can be exposed to heirs
• A sibling class of the public class cannot be exposed
to heirs – it’s truly private
• Inner classes can and often are anonymous
– adapters for event handling usually are
7/16/2015
© Charles E. Hughes 2000
197
Packages
• Package declaration is file based. All classes in the
same file belong to the same package.
• The package declaration can start a file. Its name is
usually in a dotted notation signifying its placement in
a directory hierarchy.
package com.imagesoft.image.utils;
// stored in myclassbase/com/imagesoft/image/utils
• Packages partition name space, providing a means to
prevent name collision.
7/16/2015
© Charles E. Hughes 2000
198
Package as Trusted Group
• In C++, the concept of friend is used to open up a
class an outsider (class or C function)
• Packages are a bit more refined in that they define a
group to whom you may choose to expose a selected
part of your inner feelings (non-public parts and
services).
• Package is the default protection level
7/16/2015
© Charles E. Hughes 2000
199
Dealing with Exceptions
• Exceptions can arise from all sorts of sources
the JVM detecting a fatal error
the JVM recognizing a problem e.g., index bound
a java object encountering an unusual condition
e.g., file troubles, stack underflow
• The above fall into three categories of Throwable
Error
RunTimeException
Exception
• Errors and RunTime Exceptions are unchecked.
All other Exceptions are checked.
7/16/2015
© Charles E. Hughes 2000
200
Checked Exceptions
• You must handle a checked exceptions, e.g.,
IOException explicitly.
• You either declare that you throw the exception
public void useIO() throws IOException {
…
}
• Or, you catch the exception and handle as you see fit
try {
…
} catch (IOException e) { … }
7/16/2015
© Charles E. Hughes 2000
201
Multiple Exception Types
try {
might throw exceptions …
} catch (Exception1 e1) {
handling exception of type Excetion1 …
} catch (Exception2 e2) {
handling exception of type Excetion2 …
} catch (Exception3 e3) {
handling exception of type Excetion3 …
} finally {
//always executed, even if no exception
clean up file handling and network connections …
}
7/16/2015
© Charles E. Hughes 2000
202
Exception Hierarchy
7/16/2015
© Charles E. Hughes 2000
203
Overloading
• The signature of a method or constructor is the sequence made
up of the types of its parameters.
• Return type, parameter names and the final attribute are not part
of a signature.
• Overloading is the ability of different methods or constructors to
share the same name.
• Rule: If two methods or constructor in a class have different
signature, then they may be overloaded.
• Overloading should not hinder readability. Thus, if two methods
share the same name, they need to be semantically akin.
7/16/2015
© Charles E. Hughes 2000
204
Class Inheritance in Java
• Java uses the term extends when one class is a
subclass of another.
• This reflects the principle that a class has an is-a
relationship with its superclasses.
• Subclasses can access all public and protected
members of their ancestors – not package though.
• A subclass can override any non-final visible method
of its superclasses, but may not alter the return type.
7/16/2015
© Charles E. Hughes 2000
205
Construction of Objects
• The fields of the superclass are initialized.
• One of the constructors of the superclass is invoked.
• The fields of the referenced class are initialized.
• One of the constructors of the new class is invoked.
7/16/2015
© Charles E. Hughes 2000
206
Subtypes
• Each class defines a type All instances of the class
constitute the values of this type.
• As every instance of a subclass is also an instance of
its superclass, the type defined by the subclass is a
subtype of that defined by its superclass
• Subtype is somewhat in conflict with the idea that
subclasses extend their superclasses. But, it’s more
important now to realize that a subclass is always an
instance of its superclass, but not vice versa.
7/16/2015
© Charles E. Hughes 2000
207
Principle of Substitutability
• Java follows the “Principle of Substitutability”
– If B is a subtype of A, then we can replace any instance of A with an
instance of B in any situation with no observable effect
• Note that subtype is not the same as compatible, in that
compatibility is symmetric. Subtype is asymmetric.
• Widening and narrowing as discussed earlier apply to class
typing as well as primitives
widening is always allowed
narrowing requires explicit typecast
7/16/2015
© Charles E. Hughes 2000
208
Substitutability & Subtypes
The term subtype implies substitutability
Strongly typed languages require this property in many
more situations than just adhering to a protocol
E.g., in Java, we may insist on parameters of a certain
type –
subtypes may be used here.
We may also create arrays of a certain type –
again, subtypes work here.
Strongly typed languages require casts to adhere to
typing rules.
7/16/2015
© Charles E. Hughes 2000
209
Polymorphic Assignment
• C and other static languages require compatibility to
do assignment.
• OO languages, due to their dynamic binding, support
the more flexible concept of polymorphic assignment.
• In lhs = rhs, the rhs expression must produce a of the
type of the lhs variable.
7/16/2015
© Charles E. Hughes 2000
210
Binding in Java
• All subclasses are assumed to be subtypes
– A variable can be assigned to a parent without explicit
casting.
– Reverse requires an explicit casting.
• Variables are “self-aware”
– They know what kind of child they are
– This allows them to call the correct function
7/16/2015
© Charles E. Hughes 2000
211
Example of Binding in Java
class A {
void print(){
System.out.println("This is class a");
}
}
class B extends A {
int bnum;
void print(){
System.out.println("This is class b");
}
}
public class TestBind {
public static void main(String[] args) {
A a1 = new A();
B b1 = new B();
A a2;
B b2;
a1.print();
b1.print();
b1.bnum = 5;
a2 = b1;
a2.print();
b2 = (B) a2;
System.out.println("Bnum "+b1.bnum +" " + b2.bnum);
}
}
7/16/2015
© Charles E. Hughes 2000
212
Downcasting
• If you know an object is of a subtype of its declared type, then
you can downcast
type o1; subtype o2;
o2 = (subtype) o1; // if wrong get ClassCastException
• Safe downcasting can be done by
if (o1 isinstanceof o2) o2 = (subtype) o1;
else { // cannot downcast
}
• Note: clone always returns an Object so you must do
Mytype c = (Mytype) myobj.clone(); // safe
• Also, Collections store Objects, so casting is needed on retrieval.
7/16/2015
© Charles E. Hughes 2000
213
Overriding vs Overloading
• In C++ you can hide an superclass implementation by
overloading its name in a subclass.
• In Java you may override a method, but you can never overload it
from a subclass.
• Overriding is supported by polymorphic method invocation,
where the method selected is the one provided by the class
closest to the one of the object receiving the message.
• An overriding method m can invoke the method it overrides by
sending itself the message super.m()
• Super is also useful in constructors to select an appropriate
constructor from the parent class. Here, it must appear as the
first statement in the child’s constructor.
7/16/2015
© Charles E. Hughes 2000
214
Equality, Copying, Destroying Objects
Checking likeness
Equivalence vs Equality
Copying
shallowCopy – same handle (changing one changes other)
deepCopy (cloning) – values are copied
Destruction
Finalize
Usually cleans up stuff outside control of VM
C++ destroy does much more work
Garbage Collection
As needed versus continuous
C++ does none
Smalltalk and Java are continuous
7/16/2015
© Charles E. Hughes 2000
215
Java Assign and Clone
class CanClone implements Cloneable {
int val;
Object copy() throws CloneNotSupportedException { return this.clone(); }
}
public class TestClone {
public static void main(String[] args)throws CloneNotSupportedException {
CanClone c = new CanClone();
CanClone c2;
c.val = 5;
c2 = c;
System.out.println(" Val "+c.val + "; " + c2.val); // what’s printed?
c2.val = 4;
System.out.println(" Val "+c.val + "; " + c2.val); // what’s printed?
c2 = (CanClone) c.copy();
c2.val = 3;
System.out.println(“Val "+c.val + "; " + c2.val); // what’s printed?
}
}
7/16/2015
© Charles E. Hughes 2000
216
Day#9
7/16/2015
© Charles E. Hughes 2000
217
Object-Oriented Development
7/16/2015
© Charles E. Hughes 2000
218
Software Phases Revisited
•
Conceptualization
– Requirements – informal description of what is needed; often includes
prototype to help resolve issues
– Specifications – formal requirements; can be legal document; often includes
walkthrough with client, moderated by QA staff
•
Analysis and Modeling – identifying the software components
•
Design – designing the components and their relationships
•
Implementation – making it real
•
Integration – putting the parts together with each other and existing
components
•
Maintenance – fixing, improving, adapting
7/16/2015
© Charles E. Hughes 2000
219
OO Process
• Identify classes from problem space; often better to
identify classes from problem domain
• Identify semantics (states, services) of classes
• Identify relationships among classes
• Define the class interfaces (protocols, contracts)
• Implement the classes
• Iterate
7/16/2015
© Charles E. Hughes 2000
220
Issues During Analysis
• How to find objects
• How to describe the objects
• How to describe the relations and commonalties between objects
• How to use objects to structure programs
• Very often, there is no single right way
• There are a bunch of wrong ones.
7/16/2015
© Charles E. Hughes 2000
221
Identifying Objects and Classes
•
OO Analysis examines requirements from the perspective of the classes
and objects found in vocabulary of problem domain.
•
This is the first phase of object identification
–
–
–
–
–
–
–
–
People – Actors who carry out a function
Things – Physical or otherwise tangible objects
Places – Areas set aside for people or things(often collections)
Organizations – Collections having a mission
Concepts – Principles or ideas (transactions, maps, trust levels)
Events – Things that happen at a given time (mouse clicks, purchase orders)
Roles – E.g., employee, supervisor
Behaviors – E.g., can swim
•
Scenarios are very helpful here
•
Nouns usually reflect objects; Verbs usually reflect methods
– Scenarios demonstrate various ways that the system might be used
7/16/2015
© Charles E. Hughes 2000
222
Identifying Semantics
• Determine attributes and methods
• Recognize commonalities
– Interfaces
– Abstract classes
• Domain knowledge can be very helpful here and in
previous stage.
– Sometimes a more general system is easier to design and
understand
7/16/2015
© Charles E. Hughes 2000
223
Identifying Relationships
• Containment and aggregation are easiest
• All relations should be established, plus cardinality of relations
• Sometimes leads us to recognize new abstractions
• CRC (class/responsibility/collaborator) technique
– Team members are assigned classes of objects and must role play
– Quickly identifies what services class must provide
– New objects and classes often evolve
7/16/2015
© Charles E. Hughes 2000
224
Scenarios
• It’s always good to create a scenario-driven users manual
(tutorial) for the system, before ever writing a line of code
• This supports
– Requirements (mis)understanding
– Object identification
– Object semantics
– Object interaction
– CRC sessions
– Testing
– Documentation
7/16/2015
© Charles E. Hughes 2000
225
Domain Analysis
• A generalization of the problem space analysis is
domain analysis where we look for more generic
models of the world.
– OO Design is the process of object-oriented decomposition
based on both logical (class and object structure) and
physical (module and process architecture) attributes.
– OO Programming is an implementation based on cooperating
objects, each of which is an instance of a class from some
inheritance hierarchy.
7/16/2015
© Charles E. Hughes 2000
226
Desirable Properties
• Abstraction:
– Without them we’d never manage complex tasks
• Encapsulation:
– Hide the details
• Modularity:
– Divide and Conquer
• Hierarchy:
– Is-a and Has-a
• Typing:
– Strong / weak; early / late
• Concurrency:
– It’s there for the asking
• Persistence:
– Survival of state information across executions
7/16/2015
© Charles E. Hughes 2000
227
OO Concepts Summary
• Everything is an object.
• Computation is performed by inter-objects communicating.
– A message is a request for action bundled with whatever arguments
may be necessary to complete the task.
• Each object has its own memory.
• Every object is an instance of a class.
– A class simply represents a grouping of similar objects.
• The class is a repository for behavior associated with an object.
7/16/2015
© Charles E. Hughes 2000
228
In-Class Designs
• A Spreadsheet
• Picture Programming – a child’s programming
environment
• ???
7/16/2015
© Charles E. Hughes 2000
229
Day#10
7/16/2015
© Charles E. Hughes 2000
230
Thread Programming
7/16/2015
© Charles E. Hughes 2000
231
Threads
• Thread
– A thread is a sequentially executed stream of commands
– Usually a lightweight process
• A thread is not a program
– Runs within the resources allocated to a program
• It does have its own execution context (stack, program counter,
register)
– Multiple threads of a program share resources and can refer
to common objects
• Every program has at least one thread
7/16/2015
© Charles E. Hughes 2000
232
Thread Life Cycle
Ready
Yield
Create
Start
Running
Service
Blocked
Terminate
Finished
•
•
•
•
•
Create – new thread is allocated
Running – thread is executing
Ready – thread is waiting for the processor
Blocked – thread is waiting on a requested service
Finished – thread has been stopped and deallocated
7/16/2015
© Charles E. Hughes 2000
233
Java Threads
• Like everything else, a thread is an instance of a class.
– Thread
• Part of the java.lang package
• Provides basic behaviors
–
–
–
–
–
–
Starting
Stopping
Sleeping
Yielding
Priority management
A simple form of monitors
• The run method, by default is empty
• There are two ways
– Subclass Thread and override run
– Implement the Runnable interface
7/16/2015
© Charles E. Hughes 2000
234
Sample Java Thread
class SimpleThread extends Thread {
public SimpleThread(String str) {
super(str); //sets thread’s name
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i + " " +getName());
try {
sleep((int)(Math.random() * 1000)); // one second delay
} catch (InterruptedException e) { }
}
System.out.println("DONE! " + getName());
}
}
public class TwoThreadsTest {
public static void main (String[] args) {
new SimpleThread("Jamaica").start();
new SimpleThread("Fiji").start();
}
}
7/16/2015
© Charles E. Hughes 2000
235
Creating & Starting a Thread
• Creating a thread instances the class
– No resources have been allocated to it yet
– From here, the only thing you can do is call the start method
myThread = new Thread(this,”My Thread”);
• Used as part of the Runnable interface
• “this” sets the context for the thread
• “My Thread” sets the name
myThread = new MyThreadClass(”My Thread”);
• Used when inheriting
• Context is set to the current object
• Starting a thread
myThread.start();
– Allocates the resource
– Starts the thread running
– Returns control to existing thread
7/16/2015
© Charles E. Hughes 2000
236
Ways to Delay
• Yielding the processor
myThread.sleep(1000);
– Sleeps the number of milliseconds
– Will not run even if processor becomes available
– sleep(0) sees if anything else is ready to run
– can also use yield( )
• Blocked
– Waiting on I/O
• System will schedule job when the data is available
– User defined
• Most often waiting on a shared piece of code
• Busy Wait
while (okToProceed == false) { };
– Technically stays in runnable state
– Program is constantly checking to see if a resource has become
available
– Not a good thing to do with one processor
7/16/2015
© Charles E. Hughes 2000
237
Thread or Runnable?
• Thread is a class
– Java supports only single inheritance
•
Runnable is interface
– So it can be multiply inherited
• So, use Runnable when you have to inherit from some
other class
– This is required for multithreading in applets
7/16/2015
© Charles E. Hughes 2000
238
A Bank Account
class Account {
// ...
public boolean withdraw(long amount) {
if (amount <= balance) {
long newbalance = balance - amount;
balance = newbalance;
return true;
} else
return false;
}
private long balance;
}
7/16/2015
© Charles E. Hughes 2000
239
OOPS – A Rich Race
Assume the initial balance is $1,000,000. Two
withdraw requests are made almost
simultaneously.
Balance
withdraw 1
1,000,000
1,000,000
1,000,000
1,000,000
0
0
0
0
amount<=balance
7/16/2015
withdraw 2
amount<=balance
newbalance=...;
newbalance=...;
balance=...;
balance=...;
return true;
return true;
© Charles E. Hughes 2000
240
Synchronization
Mutual exclusion of threads.
•
•
•
Each synchronized method or statement is guarded by
an object.
When entering a synchronized method or statement, the
object will be locked until the method is finished.
When the object is locked by anther thread, the current
thread must wait.
7/16/2015
© Charles E. Hughes 2000
241
Two Granularities
•
Synchronized method:
class MyClass{
synchronized void aMethod(){
statements
}
}
•
Synchronized statement:
synchronized(exp){
statements
}
7/16/2015
© Charles E. Hughes 2000
242
The Life of an Applet
7/16/2015
© Charles E. Hughes 2000
243
Applet’s Methods
The class Applet provides lots of services.
All instances of Applet respond to the messages
init()
start()
stop()
destroy()
paint(g)
-- called when browser first encounters applet
-- called when browser visits page containing applet
-- called when browser leaves page
-- called when browser decides applet is irrelevant
-- called when applet’s view is being uncovered,
or originally shown
The default versions of these functions (provided by
Applet) do nothing.
7/16/2015
© Charles E. Hughes 2000
244
Applet’s Lineage
• Applet inherits from Panel that provides a standard layout
(FlowLayout)
• Panel inherits from Container so it can add(aComponent) to its
layout
– Button, List, … are Components
• Container inherits from Component which knows how to paint(g)
its graphical appearance in Graphics context g
• Hey -- an Applet is-a Component and it has-a Components
– This makes sense if you think about it
• JApplet inherits from Applet, but disables add (EVIL).
How? add calls peer addImpl which gets error on JApplet
Overrides standard layout to be BorderLayout.
Lightweight Swing components provide double buffering.
7/16/2015
© Charles E. Hughes 2000
245
Applet’s Hierarchy Branch
java.lang.Object
|
+----java.awt.Component
|
+----java.awt.Container
|
|
+----java.awt.Panel
+----javax.swing.JComponent
|
+----java.applet.Applet
|
+----javax.swing.JApplet
7/16/2015
© Charles E. Hughes 2000
246
Putting Applet Together
import java.applet.Applet;
import java.awt.Graphics;
public class firstApplet extends Applet {
StringBuffer message;
void concat(String action) {
message.append(action);
repaint();
}
public void init() {
message = new StringBuffer();
concat("init ");
}
public void start() { concat("start "); }
public void stop() { concat("stop "); }
public void destroy() { concat("destroy "); }
public void paint(Graphics g) { g.drawString(message.toString(), 10, 20); }
}
7/16/2015
© Charles E. Hughes 2000
247
Putting Applet Together
import java.applet.Applet;
import java.awt.Graphics;
public class firstApplet extends Applet {
StringBuffer message;
void concat(String action) {
message.append(action);
repaint();
}
public void init() {
message = new StringBuffer();
concat("init ");
}
public void start() { concat("start "); }
public void stop() { concat("stop "); }
public void destroy() { concat("destroy "); }
public void paint(Graphics g) { g.drawString(message.toString(), 10, 20); }
}
7/16/2015
© Charles E. Hughes 2000
248
HTML Parameters
• The web page invokes the applet and tells it where and how big
of space it has to run
• Simplest version of an invocation
<APPLET CODE=‘myApplet.class’ WIDTH=90 HEIGHT=120>
</APPLET>
• The class file needs to be in HTML source directory or a child.
• You can also pass parameters, specify the location of the code
base, load an archive, and specify an alternative message for
non-Java browsers.
• Parameters are passed as name / value pairs
<PARAM NAME=“NumberOfUsers” VALUE=10>
<PARAM NAME=“SoundFile” VALUE=“bluemoon.au”>
7/16/2015
© Charles E. Hughes 2000
249
Acquiring Parameters
int numOfUsers = 0;
String nouString = getParameter(“NumberOfUsers”);
String annoyingSound = getParameter(“SoundFile”);
if(nouString != null)
try {
numOfUsers = Integer.parseInt(nouString);
} catch (NumberFormatExecption e) {
//use the default, no users
}
7/16/2015
© Charles E. Hughes 2000
250
Threads and Applets
• All applets commonly use threads
• Rule of thumb, if you are going to do something that is going to
take a while, spawn off a thread to do.
– Loading images or sound files
– Playing sounds
• Implement the Runnable interface to use threads in an applet
• There is a main thread, the Event Thread
– This is the one that the browser talks to
– It is the only one that will stop by default when you leave the page
– You must stop all the others
• If you do complex actions in the Event Thread, your applet
becomes totally non-responsive. – DON’T DO IT!!!!
7/16/2015
© Charles E. Hughes 2000
251
Race Conditions Uncovered
7/16/2015
© Charles E. Hughes 2000
252
Multithreaded Sort #1
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
import java.util.*;
public class EOSort extends JApplet implements Runnable {
private static int N = 8;
private static int MAX_DELAY = 500; // half second
private static int MAX_VALUE = 50; //
private Thread[ ] threads;
private int[ ] values;
private Vector v;
7/16/2015
© Charles E. Hughes 2000
253
Multithreaded Sort #2
public void init() {
Random r = new Random();
String parm = getParameter("N");
if (parm != null) N = Integer.parseInt(parm);
values = new int[N];
for (int i=0; i<N; i++)
values[i] = r.nextInt(MAX_VALUE) + 1;
}
7/16/2015
© Charles E. Hughes 2000
254
Multithreaded Sort #3
public void start() {
threads = new Thread[N];
for (int i=0; i<N; i++) {
threads[i] = new Thread(this, Integer.toString(i));
threads[i].start();
}
}
public void stop() {
for (int i=0; i<N; i++) threads[i] = null;
}
7/16/2015
© Charles E. Hughes 2000
255
Multithreaded Sort #4
public void paint(Graphics g) {
v = new Vector(N);
for (int i=0; i<N; i++) v.add(new Integer(values[i]));
g.clearRect(0, 0, getContentPane().getWidth(),
getContentPane().getHeight());
g.drawString(v.toString(), 0, 30);
}
private void swap(int i, int j) {
int temp = values[i];
values[i] = values[j];
values[j] = temp;
}
7/16/2015
© Charles E. Hughes 2000
256
Multithreaded Sort #5
public void run() {
while (threads[0] != null) {
try {
Thread.currentThread().sleep(
(int)(MAX_DELAY*Math.random()));
} catch (InterruptedException e) {}
int me = Integer.parseInt(Thread.currentThread().getName());
int left = Math.max(0,me-1);
int right = Math.min(N-1,me+1);
boolean change = false;
if (values[me] > values[right]) {swap(me, right);change=true;}
if (values[me] < values[left]) {swap(me, left);change = true;}
if (change) repaint();
}
}
}
7/16/2015
© Charles E. Hughes 2000
257
What if Multiprocessor?
• Thought Exercise
– Starting from the Java even/odd implementation, add delays
(sleep) at various points to break the atomicity of my solution.
– Discuss which placements of sleep cause semantic problems
and which do not. Explain both as best you can.
– Go back to EOSort. Design and re-implement it using critical
section(s) – synchronized blocks. It's inherently unsafe right
now.
7/16/2015
© Charles E. Hughes 2000
258
Garbage Collection
7/16/2015
© Charles E. Hughes 2000
259
Garbage Collection Strategies
• Responsibility (Reference) Count
– Suitable for Real-Time
– Does Not Detect Cycles
– Involves Continuous Overhead
• Tracing (Mark and Sweep)
– Depth First Search – Similar to Serialization
– Can avoid unmarked phase
– Can make system Appear Dead (Dreaded GC Icon in Lisp)
– Used When Needed; Sweep must include Finalization
7/16/2015
© Charles E. Hughes 2000
260
Compacting on Mark/Sweep
• Reduce heap Fragmentation
• Copying Collectors Get great Compaction
– Stop and copy swaps halves; when current half gets used up
7/16/2015
© Charles E. Hughes 2000
261
Generational Collectors
• Most objects created by most programs have very
short lives.
• Most programs create some objects that have very
long lifetimes. A major source of inefficiency in simple
copying collectors is that they spend much of their
time copying the same long-lived objects again and
again.
• Just garbage collect young objects more often than
old. Promote when around for a while.
• Can be used with mark and sweep or copy.
7/16/2015
© Charles E. Hughes 2000
262
Adaptive Collectors
• Choose technique based on current observations.
• Can change strategy over time.
7/16/2015
© Charles E. Hughes 2000
263
Incremental Collectors
• Time bounded is commonly used.
• Can also focus on youngest generational subheaps.
• Can keep all but most mature subheap at a bounded
size, so incremental garbage collection is timebounded.
– Most mature cannot be bounded.
7/16/2015
© Charles E. Hughes 2000
264
Train Algorithms
• Variant called train algorithm used in Sun HotSpot.
• Train algorithm divides mature heap into blocks (cars),
connected to make a train. Each train is on a separate track.
•
When blocks are added, they appear at end of a train, or on a
new higher numbered train.
• High numbered trains are younger, higher numbered cars on
track are younger.
• Has benefit oif clustering related objects.
• Details are in
http://www.artima.com/insidejvm/ed2/ch09GarbageCollection01.html
7/16/2015
© Charles E. Hughes 2000
265
Simple Animations
Applet Framework Examples
7/16/2015
© Charles E. Hughes 2000
266
A Calendar Applet
import java.awt.*;
import javax.swing.*;
import java.util.Calendar;
public class DigitalClock
extends JApplet implements Runnable { // must implement run()
// all can be altered by subclasses
protected Thread clockThread = null;
protected Font font = new Font("Monospaced", Font.BOLD, 48);
protected Color color = Color.green; // standard colors are class constants
public void start() {
if (clockThread == null) { // do we have a live thread already?
clockThread = new Thread(this); // runs in context of “this”
clockThread.start(); // this will send the message run() to thread context
}
}
public void stop() {
clockThread = null; // signal thread to stop
}
7/16/2015
© Charles E. Hughes 2000
267
Rest of Calendar Applet
public void run() {
while (Thread.currentThread() == clockThread) { // should I continue
repaint(); // pretty please call my paint
try { // could get interrupted
Thread.currentThread().sleep(1000); // 1 second; why not use clockThread?
} catch (InterruptedException e) { }
}
}
public void paint(Graphics g) {
Calendar calendar = Calendar.getInstance(); // constructs
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
g.setFont(font);
g.setColor(color);
// not needed in old fashion applets
g.clearRect(0, 0, getContentPane().getWidth(), getContentPane().getHeight());
g.drawString(hour + ":" + minute / 10 + minute % 10 +
":" + second / 10 + second % 10, 10, 60);
}
}
7/16/2015
© Charles E. Hughes 2000
268
Extending the Calendar Applet
import java.awt.Color;
public class DigitalClock2 extends DigitalClock {
public void init() {
String param = getParameter("color");
if ("red".equals(param)) {
color = Color.red;
} else if ("blue".equals(param)) {
color = Color.blue;
} else if ("yelow".equals(param)) {
color = Color.yellow;
} else if ("orange".equals(param)) {
color = Color.orange;
} else {
color = Color.green;
}
}
}
7/16/2015
© Charles E. Hughes 2000
269
Calendar HTML – if Swing okay
<!--DigitalClock2.html-->
<HTML>
<HEAD>
<TITLE> Digital Clock Applet2 </TITLE>
</HEAD>
<BODY BGCOLOR=white>
<CENTER>
<H1> The Better Digital Clock Applet</H1>
<P>
<APPLET CODE=DigitalClock2.class
WIDTH=250 HEIGHT=80>
<PARAM NAME=color VALUE=red>
</APPLET>
</CENTER>
</BODY>
</HTML>
7/16/2015
© Charles E. Hughes 2000
270
Scrolling Banner Applet
import javax.swing.*;
import java.awt.*;
public class ScrollingBanner extends JApplet implements Runnable {
protected Thread bannerThread;
protected String text;
protected Font font = new java.awt.Font("Sans-serif", Font.BOLD, 24);
protected int x, y;
protected int delay = 100;
protected int offset = 1;
protected Dimension d;
public void init() {
// get parameters "delay" and "text"
String att = getParameter("delay");
if (att != null) delay = Integer.parseInt(att);
att = getParameter("text");
if (att != null) text = att;
else text = "Scrolling banner.";
// set initial position of the text
d = getSize();
x = d.width;
y = font.getSize();
}
7/16/2015
© Charles E. Hughes 2000
271
Scrolling Banner Applet # 2
public void paint(Graphics g) {
// get the font metrics to determine the length of the text
g.setFont(font);
FontMetrics fm = g.getFontMetrics(); // properties are function of font and screen
int length = fm.stringWidth(text);
// adjust the position of text from the previous frame
x -= offset;
// if the text is completely off to the left end
// move the position back to the right end
if (x < -length) x = d.width;
// set the pen color and draw the background
g.setColor(Color.black);
g.fillRect(0,0,d.width,d.height);
// set the pen color, then draw the text
g.setColor(Color.green);
// ******** Flicker, Flicker little banner ********
g.clearRect(0, 0, getContentPane().getWidth(), getContentPane().getHeight());
g.drawString(text, x, y);
}
7/16/2015
© Charles E. Hughes 2000
272
Scrolling Banner Applet # 3
public void start() {
bannerThread = new Thread(this);
bannerThread.start();
}
public void stop() {
bannerThread = null;
}
public void run() {
while (Thread.currentThread() == bannerThread) {
try {
Thread.currentThread().sleep(delay);
}
catch (InterruptedException e) { }
repaint();
}
}
}
7/16/2015
© Charles E. Hughes 2000
273
Double Buffering
import java.awt.*;
public class ScrollingBanner2 extends ScrollingBanner {
protected Image image;
// The off-screen image
protected Graphics offscreen; // The off-screen graphics
public void paint(Graphics g) {
// create the offscreen image if it is the first time
if (image == null) {
image = createImage(d.width, d.height); // in essence a bitmap
offscreen = image.getGraphics(); // this provides access to graphics
}
// draw the current frame into the off-screen image
// use parent’s paint – it worked fine, we just don’t want to see it working
super.paint(offscreen);
// copy the off-screen image to the screen
g.drawImage(image, 0, 0, this);
}
}
7/16/2015
© Charles E. Hughes 2000
274
Bouncing Ball Applet
import java.awt.*;
import javax.swing.*;
public class BouncingBall
extends JApplet implements Runnable {
protected Color color = Color.green;
protected int radius = 20;
protected int x, y;
protected int dx = -2, dy = -4;
protected Image image;
protected Graphics offscreen;
protected Dimension d;
public void init() {
String att = getParameter("delay");
if (att != null) {
delay = Integer.parseInt(att); // class service of Integer wrapper class
}
d = getSize(); // available to init but not applet constructor
x = d.width * 2 / 3;
y = d.height - radius;
}
7/16/2015
© Charles E. Hughes 2000
275
Bouncing Ball Applet # 2
public void paint(Graphics g) {
// create the off-screen image buffer, if it is invoked the first time
if (image == null) {
image = createImage(d.width, d.height); // in essence a bitmap
offscreen = image.getGraphics(); // this provides access to graphics
}
// draw the background
offscreen.setColor(Color.white);
offscreen.fillRect(0,0,d.width,d.height); // clear off-screen graphics
// adjust the position of the ball
// reverse the direction if it touches any of the four sides
if (x < radius || x > d.width - radius) dx = -dx;
if (y < radius || y > d.height - radius) dy = -dy;}
x += dx; y += dy;
// draw the ball
offscreen.setColor(color);
offscreen.fillOval(x - radius, y - radius, radius * 2, radius * 2);
// copy the off-screen image to the screen
g.drawImage(image, 0, 0, this);
}
7/16/2015
© Charles E. Hughes 2000
276
Bouncing Ball Applet # 3
// The animation applet idiom
protected Thread bouncingThread;
protected int delay = 100;
public void start() {
bouncingThread = new Thread(this);
bouncingThread.start();
}
public void stop() {
bouncingThread = null;
}
public void run() {
while (Thread.currentThread() == bouncingThread) {
try {
Thread.currentThread().sleep(delay);
} catch (InterruptedException e) { }
repaint();
}
}
}
7/16/2015
© Charles E. Hughes 2000
277
Interface Inheritance
• While classes descend from a tree rooted at Object,
interfaces have no top.
• While class inheritance is single, interface inheritance
can be multiple. This causes no problems since
interfaces implement nothing, and add no parts.
• Interfaces interact in the Java typing system. In fact
that is often their purpose.
• Interfaces sometimes are used as markers, providing
no contract. Examples are Cloneable and Serializable.
7/16/2015
© Charles E. Hughes 2000
278
Interfaces as Types
• Every interface is a subtype of Object.
Every primitive and array type is a subtype of Object.
– that’s so there is a universal type in the type system.
• If a class or interface C extends another class or
interface T, then C is a subtype of T.
• If class C implement interface T, C is a subtype of T.
• If C is a subtype of T, then C[ ] is a subtype of T[ ].
7/16/2015
© Charles E. Hughes 2000
279
Name Conflicts
• Name collision can occur in Java when a class
extends a parent and implements multiple interfaces,
or even when an interface extends multiple interfaces.
• If two methods have the same name and
different signatures – overload
same signature, same return type – collapse to one
with union of the exceptions they throw
same signature, different return types – error
7/16/2015
© Charles E. Hughes 2000
280
Hiding of static Members
• Static variables and methods are not overridden, they
are hidden.
• This is because static binding is determined at
compile time, not at run-time.
• Hiding is confusing and error-prone.
7/16/2015
© Charles E. Hughes 2000
281
A Riddle – What is the Output?
class St {
static void overrideme() { System.out.println("St"); }
public static void main(String args[]) {
St x1 = new St2();
x1.overrideme();
St2 x2 = new St2();
x2.overrideme();
System.out.println("Press Ctrl-C to stop");
while (true);
}
}
class St2 extends St {
static void overrideme() { System.out.println("St2"); }
}
7/16/2015
© Charles E. Hughes 2000
282
Exercise #3
• Run the example application on the previous slide.
Explain the output that it produces.
• Add an instance method to both St and St2 that
mimics overrideme(). You will need to give it a
different name, say instance_override(). Create an
instance of St and invoke its instance_override()
service. What happens now?
• What does this say about binding in Java?
7/16/2015
© Charles E. Hughes 2000
283
Why no Templates in Java?
• C++ supports a form or genericity through template classes and
methods. For instance the Standard Template Library (STL)
defines a template class vector so you can declare kinds of
vectors like
vector<int> v(10);
vector<Employee> e(7); // Employee is a user class
• Templates are nice, but they are usually a compromise based on
the lack of a universal type.
• In Java, Vector always refers to a vector of objects.
• Of course, Java’s way forces casting and is not as informative for
compiler optimization – the almighty nanosecond god of C.
• Wait – Generics are on their way in Java!!!
7/16/2015
© Charles E. Hughes 2000
284
Headers versus Interfaces
• C++ header (.h) works with an implementation (.cpp), and
together they define the class.
• In Java the interface and class have an implementation relation,
but the interface is not married to to just one class.
• C++ header contains the interface, some implementation (inlines,
for instance) and all fields, both public and private.
• Java interfaces contain no implementation and no parts. Again,
it’s a contract to which many classes may agree.
7/16/2015
© Charles E. Hughes 2000
285
Delegation versus Inheritance
• Delegation is the act of an object delegating
responsibility for the handling of a service to some
other object.
• To some degree, aggregation can be used for
delegation, in that I could have a copy of the objects to
whom I pass responsibility as one of my parts.
• Often though, delegation allows the delegates to
declare their interest, and the delegator has no a priori
idea of who will be interested in these messages.
7/16/2015
© Charles E. Hughes 2000
286
Simple Delegation
• This is used in the AWT extensively to support peers.
• In abstract class Component one sees
// notice a peer is not serializable – why?
transient ComponentPeer peer;
…
public void paintAll(Graphics g) {
ComponentPeer peer = this.peer;
if (visible && (peer != null)) {
validate();
if (peer instanceof java.awt.peer.LightweightPeer) { //marker
paint(g);
} else { peer.paint(g); } } }
• AWT components delegate; Swing take care of their own display.
7/16/2015
© Charles E. Hughes 2000
287
Delegation to Listeners
• This is an inversion of simple delegation, in which the
delegatees register their interest in an event. The
delegator is just responsible to notify them of the
event (message, exception, whatever).
• In Java those willing to be delegated a service are
called listeners. They listen for some event, and then
perform some appropriate action.
• The new event model in Java (details later) is based
totally on delegation of events to interested listeners.
7/16/2015
© Charles E. Hughes 2000
288
Adapters – Dedicated Listeners
• Adapters are specialized objects dedicated to
listening for just one event type from one source.
JLabel pressMe = new JLabel();
pressMe.setText(“Press Me");
pressMe.addMouseListener(new java.awt.event.MouseAdapter(){
public void mousePressed(MouseEvent e) {
pressMe_mousePressed(e);
}}
);
• This is an example of an anonymous class that is
subclassed off an abstract class MouseAdapter. See
next page for details.
7/16/2015
© Charles E. Hughes 2000
289
MouseAdapter – a boutique
public abstract class MouseAdapter implements MouseListener {
public void mouseClicked(MouseEvent e) { }
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
}
• Provides empty implementations, so you need override only
those events that you wish to meaningfully delegate.
7/16/2015
© Charles E. Hughes 2000
290
Frameworks
7/16/2015
© Charles E. Hughes 2000
291
What is a Framework?
• Frameworks is a collection of abstractions that
support a particular kind of applications
• Frameworks in Java are made up of classes,
interfaces and policies that can enforce proper use
and interaction among the various components.
• Frameworks often impose an inversion of control in
which some base object in the framework controls
progress and high-level interactions. Your obligation
is to plug in specialized pieces that make the result
appropriate to your needs.
7/16/2015
© Charles E. Hughes 2000
292
Frameworks are Hard!!
• Creating a useful framework is notoriously hard.
• Creating one that people will use, forgoing their impulse to be in
control is even harder.
• There are only a few existing examples of successful
frameworks. These include:
The model-view-controller framework / paradigm from Smalltalk
The collection framework, also originally from Smalltalk
The applet framework from Sun
To give dominance its due, MFC and DirectX from Microsoft
7/16/2015
© Charles E. Hughes 2000
293
The Applet Framework
• Primarily supports reactive style of interaction,
commonly invoked from a browser.
• It handles user interface, you tell it the widgets.
• It handles user interaction, you get call backs on
events that you might handle.
• It protects you from others, and the environment from
you.
7/16/2015
© Charles E. Hughes 2000
294
What you Plug-In
• init() – called when page loaded; default is { }
• start() – called when page entered; default is { }
• stop() – called when page left; default is { }
• destroy() – called when page discarded; default is { }
• paint(Graphics g) – called by update when GUI is refreshed
– update(g) for Applet is {g.clearRect(0, 0, width, height); paint(g);}
– update(g) for JApplet is { paint(g); }
7/16/2015
© Charles E. Hughes 2000
295
Some Care to be Taken
• Before init, you can depend on nothing about the user interface,
including its size.
• During init, you cannot depend on any aspects of the user
interface being settled on except the window size.
• All these services are invoked by the browser’s thread. If you
spend too much time here, your applet will appear dead, and so
will its sandbox.
• You never call paint() or update() directly. You call repaint() which
says pretty please update me. If you do this on a busy thread, the
repaints may never be effected.
7/16/2015
© Charles E. Hughes 2000
296
Simple Animations
Applet Framework Examples
7/16/2015
© Charles E. Hughes 2000
297
Patterns
7/16/2015
© Charles E. Hughes 2000
298
Patterns
•
Patterns are a continually occurring problem and a corresponding core
solution.
•
Our goal is to create meta-solutions.
•
A common pattern is the problem of managing user interfaces – the AWT
was an attempt at such an abstraction; Swing is a better attempt.
•
One of the most common patterns in software design is the problem of
managing collections of objects – a core solution would abstract out the
commonality.
•
Yet a third pattern is problem of iterating over collections; a pattern
within a pattern.
•
Actually the Scheduler class we wrote earlier and the Calendar class we
used uncover the common need for a class with just one instance.
7/16/2015
© Charles E. Hughes 2000
299
History of Design Patterns
• Patterns are generic solutions to recurring problems.
• The concept of patterns comes form the landmark
work of Christopher Alexander (1979) concerning a set
of 253 patterns that describe all architectural designs.
• Gamma et al. (1995) adapted this to software coming
up with 23 patterns.
7/16/2015
© Charles E. Hughes 2000
300
Gamma’s 23 Patterns
• Creational Patterns
Abstract Factory Builder
Prototype
Singleton
Factory Method
• Structural Pattern
Adapter
Decorator
Proxy
Composite
Flyweight
Bridge
Façade
• Behavioral Patterns
Command
Interpreter
Iterator
Mediator
Memento
Observer
State
Strategy
Template Method
Visitor
Chain of Responsibility
7/16/2015
© Charles E. Hughes 2000
301
Recognizing Patterns
• Patterns are seen when we factor out commonality.
• Factoring by recurring code is old and led to libraries.
• Factoring by inheritance is the basis of OO.
• Factoring by delegation is often used when
inheritance is not appropriate – the pattern is seen in
many parts of the hierarchy, but is not common to
Object.
7/16/2015
© Charles E. Hughes 2000
302
The Template Pattern
More Animation Examples
7/16/2015
© Charles E. Hughes 2000
303
Design Pattern:Template
Category
Behavioral design pattern.
Intent
Define the skeleton of an algorithm in a method, deferring
some steps to subclasses, thus allowing the subclasses to
redefine certain steps of the algorithm.
Applicability
•
•
to implement the invariant parts of an algorithm once and
leave it up to the subclasses to implement the behavior
that can vary.
to factorize and localize the common behavior among
subclasses to avoid code duplication.
7/16/2015
© Charles E. Hughes 2000
304
The Generic Animation
• In all our previous animations, we saw the need for the
common services of
– start()
– stop()
– run()
– setDelay(int)
– getDelay()
7/16/2015
© Charles E. Hughes 2000
305
Base Animation Class
import java.awt.*;
import javax.swing.*;
public class AnimationApplet extends Japplet implements Runnable {
public void start() {
animationThread = new Thread(this);
animationThread.start();
}
public void stop() {
animationThread = null;
}
public void run() {
while (Thread.currentThread() == animationThread) {
try {
Thread.currentThread().sleep(delay);
} catch (InterruptedException e) {}
repaint();
}
}
final public void setDelay(int delay) { // cannot be overridden; pattern for beans
this.delay = delay;
}
final public int getDelay() { // cannot be overridden; pattern for beans
return delay;
}
protected Thread animationThread;
private int delay = 100; // all who wish to change delay must use service
}
7/16/2015
© Charles E. Hughes 2000
306
Redone Clock
import java.awt.*;
import java.util.Calendar;
public class DigitalClock3 extends AnimationApplet {
public DigitalClock3() {
setDelay(1000); // change from default
}
public void paint(Graphics g) {
Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
g.setFont(font);
g.setColor(color);
g.clearRect(0, 0, getContentPane().getWidth(), getContentPane().getHeight());
g.drawString(hour + ":" + minute / 10 + minute % 10 +
":" + second / 10 + second % 10, 10, 60);
}
protected Font font = new Font("Monospaced", Font.BOLD, 48);
protected Color color = Color.green;
}
7/16/2015
© Charles E. Hughes 2000
307
DBAnimation
Here for your reading pleasure
I will focus on how JPanel
overcomes this need
7/16/2015
© Charles E. Hughes 2000
308
Double Buffering Class
import java.awt.*;
public abstract class DBAnimationApplet extends AnimationApplet {
final public void paint(Graphics g) {
if (doubleBuffered) {
paintFrame(offscreen); // children plug in their paint here
g.drawImage(im, 0, 0, this);
} else {
paintFrame(g); // children plug in their paint here
}
}
final public void init() {
d = getSize();
im = createImage(d.width, d.height);
offscreen = im.getGraphics();
initAnimator();
}
7/16/2015
© Charles E. Hughes 2000
309
Double Buffering Class
protected void initAnimator() { } // child plugs in here, if needed
abstract protected void paintFrame(Graphics g); // the main hook
protected DBAnimationApplet(boolean doubleBuffered) {
this.doubleBuffered = doubleBuffered;
}
protected DBAnimationApplet() {
this( true);
}
protected boolean doubleBuffered;
protected Dimension d;
protected Image im;
protected Graphics offscreen;
}
7/16/2015
© Charles E. Hughes 2000
310
Bouncing Ball2
import java.awt.*;
public class BouncingBall2 extends DBAnimationApplet {
public BouncingBall2() {
super(true); // double buffering
}
protected void initAnimator() { // plugged in to parent template
String att = getParameter("delay");
if (att != null)
setDelay(Integer.parseInt(att));
x = d.width * 2 / 3 ;
y = d.height - radius;
}
7/16/2015
© Charles E. Hughes 2000
311
Bouncing Ball2 # 2
protected void paintFrame(Graphics g) { // must plug this hook method in
g.setColor(Color.white);
g.fillRect(0,0,d.width,d.height);
if (x < radius || x > d.width - radius) {
dx = -dx;
}
if (y < radius || y > d.height - radius) {
dy = -dy;
}
x += dx; y += dy;
g.setColor(color);
g.fillOval(x - radius, y - radius, radius * 2, radius * 2);
}
protected int x, y;
protected int dx = -2, dy = -4;
protected int radius = 20;
protected Color color = Color.green;
}
7/16/2015
© Charles E. Hughes 2000
312
Bouncing Ball2J
import java.awt.*;
import javax.swing.*;
public class BouncingBall2J extends Japplet implements Runnable {
public void init() {
String att = getParameter("delay");
if (att != null) delay = Integer.parseInt(att);
x = getWidth() * 2 / 3 ; y = getHeight() - radius;
getContentPane().add(canvas);
}
public void start() {
animationThread = new Thread(this); animationThread.start();
}
public void stop() { animationThread = null; }
public void run() {
while (Thread.currentThread() == animationThread) {
try {
Thread.currentThread().sleep(delay);
} catch (InterruptedException e) { }
repaint();
}
}
7/16/2015
© Charles E. Hughes 2000
313
Bouncing Ball2J #2
public void paint(Graphics g) {
if (x < radius || x > getWidth() - radius) dx = -dx;
if (y < radius || y > getHeight() - radius) dy = -dy;
x += dx; y += dy;
canvas.repaint();
}
private
private
private
private
Thread animationThread;
BallCanvas canvas = new BallCanvas();
Color color = Color.green;
int x, y, delay = 100, dx = -2, dy = -4, radius = 20;
class BallCanvas extends JPanel {
public void paint(Graphics g) {
g.setColor(Color.white);
g.fillRect(0,0,getWidth(),getHeight());
g.setColor(color);
g.fillOval(x - radius, y - radius, radius * 2, radius * 2);
}
}
}
7/16/2015
© Charles E. Hughes 2000
314
Animator Class
import java.awt.*;
public class Animator
implements Runnable {
public Animator(Component comp) { this.comp = comp; }
final public void setDelay(int delay) { this.delay = delay; }
final public int getDelay() { return delay; }
public void start() {
animationThread = new Thread(this); animationThread.start();
}
public void stop() { animationThread = null; }
public void run() {
while (Thread.currentThread() == animationThread) {
try { Thread.sleep(delay); } catch (InterruptedException e){ }
comp.repaint();
}
}
protected Component comp;
private int delay = 100;
protected Thread animationThread;
}
7/16/2015
© Charles E. Hughes 2000
315
Bouncing Ball3J
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BouncingBall3J extends JApplet {
public BouncingBall3J() {
canvas = new BouncingBallJPanel(); animator = new Animator(canvas);
getContentPane().add(canvas, BorderLayout.CENTER);
controlPanel = new JPanel(); controlPanel.setLayout(new GridLayout(1,0));
JButton startButton = new JButton("start");
startButton.setToolTipText("Get the ball moving.");
controlPanel.add(startButton);
JButton stopButton = new JButton("stop");
stopButton.setToolTipText("Stop the ball.");
controlPanel.add(stopButton);
String[ ] ballColors = {"red", "green", "blue"};
JComboBox choice = new JComboBox(ballColors);
controlPanel.add(choice);
getContentPane().add(controlPanel,BorderLayout.SOUTH);
startButton.addActionListener(new StartCommand());
stopButton.addActionListener(new StopCommand());
colorChoice.addItemListener(new ColorChoiceHandler());
}
7/16/2015
© Charles E. Hughes 2000
316
Bouncing Ball3J #2
public void init() {
String att = getParameter("delay");
if (att != null) {
int delay = Integer.parseInt(att);
animator.setDelay(delay);
}
canvas.initCanvas();
}
public void start() {
animator.start();
}
public void stop() {
animator.stop();
}
protected BouncingBallJPanel canvas;
protected Animator animator;
protected JPanel controlPanel;
7/16/2015
© Charles E. Hughes 2000
317
Bouncing Ball3J #3
protected class StartCommand implements ActionListener {
public void actionPerformed(ActionEvent event) {
start();
}
}
protected class StopCommand implements ActionListener {
public void actionPerformed(ActionEvent event) {
stop();
}
}
7/16/2015
© Charles E. Hughes 2000
318
Bouncing Ball3J #4
protected class ColorChoiceHandler implements ItemListener {
public void itemStateChanged(ItemEvent event) {
JComboBox choice = (JComboBox) event.getSource();
if (choice != null) {
if ("red".equals(event.getItem()))
canvas.setBallColor(Color.red);
else if ("green".equals(event.getItem()))
canvas.setBallColor(Color.green);
else if ("blue".equals(event.getItem()))
canvas.setBallColor(Color.blue);
}
canvas.repaint();
}
}
}
7/16/2015
© Charles E. Hughes 2000
319
Bouncing Ball Panel
import java.awt.*;
import javax.swing.*;
public class BouncingBallJPanel extends JPanel {
public void initCanvas() {
x = getWidth() * 2 / 3 ; y = getHeight() - radius;
}
public void paint(Graphics g) {
g.setColor(Color.white); g.fillRect(0, 0, getWidth(), getHeight());
if (x < radius || x > getWidth() - radius) dx = -dx;
if (y < radius || y > getHeight() - radius) dy = -dy;
x += dx; y += dy;
g.setColor(ballcolor);
g.fillOval(x - radius, y - radius, radius * 2, radius * 2);
}
public void setBallColor(Color c) {
ballcolor = c;
}
public void setBallPosition(int x, int y) {
this.x = x; this.y = y;
}
protected int x, y, dx = -2, dy = -4, radius = 20;
protected Color ballcolor = Color.red;
}
7/16/2015
© Charles E. Hughes 2000
320
Template Method Pattern
• The Applet, JApplet, AnimationApplet and DBAnimationApplet
classes are examples of the Template Method pattern.
• All child classes share common functionality.
• The common behaviors are encapsulated in methods, some of
which are final to prevent modification.
• The common behaviors often are templates (wrappers) with user
actions plugged in. The plug-ins are called hook methods.
• Some user hooks are required, so the parent class makes them
abstract. Some are optional, so the parent class provides a
default, often empty implementation.
7/16/2015
© Charles E. Hughes 2000
321
Exercise #4
• Create a child class of BouncingBall3J that handles
multiple balls, each with its own color.
7/16/2015
© Charles E. Hughes 2000
322
The Strategy Pattern
Generic Algorithm Examples
7/16/2015
© Charles E. Hughes 2000
323
Design Pattern: Strategy
Category
Behavioral design pattern.
Intent
Define a family of algorithms, encapsulate each one, and make
them interchangeable.
Applicability
•
•
•
•
many related classes differ only in their behavior.
you need different variants of an algorithm.
an algorithm uses data that clients shouldn't know about.
a class defines many behaviors, and these appear as multiple
conditional statements in its methods.
7/16/2015
© Charles E. Hughes 2000
324
Strategy
7/16/2015
© Charles E. Hughes 2000
325
The Generic Function
• Many components can be built around the idea of functions that
different only in some small aspect of their overall behaviors. The
idea is that we can plug in interchangeable components for these
aspects.
– A plotter needs plot functions
– A Hash table needs a hashCode() function
– A Sorted list needs a sort() function
– An algorithm animator needs an algorithm function
– An AWT component needs a LayoutManager object
– A Swing component needs a look and feel object
7/16/2015
© Charles E. Hughes 2000
326
Base Plotter Class (strategy)
import java.awt.*;
import javax.swing.*;
public abstract class Plotter extends JApplet {
public abstract double func(double x);
public void init() {
d = getSize();
String att = getParameter("xratio");
if (att != null) xratio = Integer.parseInt(att);
att = getParameter("yratio");
if (att != null) yratio = Integer.parseInt(att);
att = getParameter("xorigin");
if (att != null) xorigin = Integer.parseInt(att);
else xorigin = d.width / 2;
att = getParameter("yorigin");
if (att != null) yorigin = Integer.parseInt(att);
else yorigin = d.height / 2;
}
public void paint(Graphics g) {
drawCoordinates(g);
plotFunction(g);
}
7/16/2015
© Charles E. Hughes 2000
327
Base Plotter Class #2
/** the dimension of the viewing area */
protected Dimension d;
/** The color used for plotting */
protected Color color = Color.black;
/** The position of the origin of the coordinate system */
protected int xorigin, yorigin;
/** The number of pixels between 0 and 1 in x and y direction */
protected int xratio = 100, yratio = 100;
protected void plotFunction(Graphics g) {
for (int px = 0; px < d.width; px++) {
try {
double x = (double)(px - xorigin) / (double)xratio;
double y = func(x);
// hook -- the generic function to plot
int py = yorigin - (int) (y * yratio);
g.fillOval(px - 1, py - 1, 3, 3);
} catch (Exception e) { }
// in case your function is evil
}
}
7/16/2015
© Charles E. Hughes 2000
328
Base Plotter Class #3
protected void drawCoordinates(Graphics g) {
g.setColor(Color.white); g.fillRect(0, 0, d.width, d.height);
g.setColor(color);
g.drawLine(0, yorigin, d.width, yorigin); g.drawLine(xorigin, 0, xorigin, d.height);
g.setFont(new Font("TimeRoman", Font.PLAIN, 10));
int I, px, py = yorigin + 12;
g.drawString("0", xorigin + 2, py);
for (i=1, px = xorigin + xratio; px < d.width; px += xratio) {
g.drawString(Integer.toString(i++), px - 2, py);
g.drawLine(px, yorigin - 2, px, yorigin + 2);
}
for (i = -1, px = xorigin - xratio; px >= 0; px -= xratio) {
g.drawString(Integer.toString(i--), px - 2, py);
g.drawLine(px, yorigin - 2, px, yorigin + 2);
}
for (i=1, px = xorigin + 4, py = yorigin - yratio; py >= 0; py -= yratio) {
g.drawString(Integer.toString(i++), px, py + 4);
g.drawLine(xorigin - 2, py, xorigin + 2, py);
}
for (i=-1, py = yorigin + yratio; py < d.height; py += yratio) {
g.drawString(Integer.toString(i--), px, py + 4);
g.drawLine(xorigin - 2, py, xorigin + 2, py);
}
}
}
7/16/2015
© Charles E. Hughes 2000
329
Uses of the Plotter (contexts)
public class PlotCosine extends Plotter {
public double func(double x) { // template
return Math.cos(x); // actual hook method
}
}
public class PlotSine extends Plotter {
public double func(double x) { // template
return Math.sin(x); // actual hook method
}
}
public class PlotLog extends Plotter {
public double func(double x) { // template
return Math.log(x); // actual hook method
}
}
public class PlotSqrt extends Plotter {
public double func(double x) { // template
return Math.sqrt(x); // actual hook method
}
}
7/16/2015
© Charles E. Hughes 2000
330
HTML for Plotter Demo
<!--PlotterDemo.html-->
<HTML><TITLE> Java Demo: Function Plotter </TITLE>
<BODY>
<HR>
<CENTER><H1> Function Plotter </H1></CENTER>
<H2> y = sin(x) </H2>
<APPLET CODE="PlotSine.class" WIDTH=700 HEIGHT=300></APPLET>
<HR><H2> y = cos(x) </H2>
<APPLET CODE="PlotCosine.class" WIDTH=700 HEIGHT=300></APPLET>
<HR><H2> y = log(x) </H2>
<APPLET CODE="PlotLog.class" WIDTH=400 HEIGHT=300>
<PARAM NAME=xorigin value="0">
</APPLET>
<HR>
<H2> y = sqrt(x) </H2>
<APPLET CODE="PlotSqrt.class" WIDTH=400 HEIGHT=300>
<PARAM NAME=xorigin VALUE="0"><PARAM NAME=yorigin VALUE="280">
</APPLET>
</BODY>
</HTML>
7/16/2015
© Charles E. Hughes 2000
331
Interface for Functions
// We will use this to create a collection of functors
// each of which represents a function
interface Function {
double apply(double x);
}
public class Cosine implements Function {
public double apply(double x) {
return Math.cos(x);
}
}
public class Sine implements Function {
public double apply(double x) {
return Math.sin(x);
}
}
7/16/2015
© Charles E. Hughes 2000
332
MultiPlotter Class
import java.awt.*;
public abstract class MultiPlotter extends Plotter {
abstract public void initMultiPlotter();
public void init() {
super.init();
initMultiPlotter();
}
final public void addFunction(Function f, Color c) {
if (numOfFunctions < MAX_FUNCTIONS && f != null) {
functions[numOfFunctions] = f;
colors[numOfFunctions++] = c;
}
}
7/16/2015
© Charles E. Hughes 2000
333
MultiPlotter Class #2
protected void plotFunction(Graphics g) {
for (int i = 0; i < numOfFunctions; i++) {
if (functions[i] != null) {
Color c = colors[i];
if (c != null)
g.setColor(c);
else
g.setColor(Color.black);
for (int px = 0; px < d.width; px++) {
try {
double x = (double) (px - xorigin) / (double) xratio;
double y = functions[i].apply(x);
int py = yorigin - (int) (y * yratio);
g.fillOval(px - 1, py - 1, 3, 3);
} catch (Exception e) { } // I still don’t trust my users
}
}
}
}
7/16/2015
© Charles E. Hughes 2000
334
MultiPlotter Class #3
public double func(double x) {
return 0.0;
}
protected static int MAX_FUNCTIONS = 5;
protected int numOfFunctions = 0;
protected Function functions[ ] = new Function[MAX_FUNCTIONS];
protected Color colors[ ] = new Color[MAX_FUNCTIONS];
}
7/16/2015
© Charles E. Hughes 2000
335
Plot Sine and Cosine
import java.awt.Color;
public class PlotSineCosine extends MultiPlotter {
public void initMultiPlotter() {
addFunction(new Sine(), Color.green);
addFunction(new Cosine(), Color.blue);
}
}
7/16/2015
© Charles E. Hughes 2000
336
Strategy Pattern
• The Plotter and MultiPlotter are examples of the
Strategy pattern.
• The Strategy pattern is a variation on the Template
Method pattern in which the hook method and
template method reside in different classes, the
Strategy and the Context.
• Notice the connection between the MultiPlotter and its
functors is an abstract coupling. The plotter has no
idea what functions are being represented. It just
knows they obey a contract – supply apply(double).
7/16/2015
© Charles E. Hughes 2000
337
Exercise #5
• Get rid of the use of parallel arrays in MultiPlotter,
instead creating a new inner class that encapsulates a
pair <function,color>.
• Extra challenge – use a List of these pairs, rather than
an array. This will allow us to shed the arbitrary limit of
five functions. The list, with its ability to iterate over
anything is a great example of abstract coupling. Lists
use the Iterator pattern.
7/16/2015
© Charles E. Hughes 2000
338
Animating Algorithms
public abstract class AlgorithmAnimator
extends DBAnimationApplet {
// the hook method
abstract protected void algorithm();
// the template method
public void run() {
algorithm();
}
final protected void pause() {
if (Thread.currentThread() ==
animationThread) {
try {
Thread.sleep(delay);
} catch (InterruptedException e) {}
repaint();
}
}
}
7/16/2015
© Charles E. Hughes 2000
339
Animating Sort 1
import java.awt.*;
public class Sort extends AlgorithmAnimator {
<Method scramble()>
<Method paintFrame()>
<Method bubbleSort()>
<Method quickSort()>
<Method initAnimator()>
<Method algorithm()>
<Method swap()>
// the array to be sorted
protected int
arr[];
// the name of the algorithm to be animated
protected String algName;
}
7/16/2015
© Charles E. Hughes 2000
340
Scramble
protected void scramble() {
arr = new int[getSize().height / 2];
for (int i = arr.length; --i >= 0;) {
arr[i] = i;
}
for (int i = arr.length; --i >= 0;) {
int j = (int)(i * Math.random());
swap(arr, i, j);
}
}
private void swap(int a[], int i, int j) {
int T;
T = a[i]; a[i] = a[j]; a[j] = T;
}
7/16/2015
© Charles E. Hughes 2000
341
Visualize Array
protected void paintFrame(Graphics g) {
Dimension d = getSize();
g.setColor(Color.white);
g.fillRect(0, 0, d.width, d.height);
g.setColor(Color.black);
int y = d.height - 1;
double f = d.width / (double) arr.length;
for (int i = arr.length; --i >= 0; y -= 2)
{
g.drawLine(0, y, (int)(arr[i] * f), y);
}
}
7/16/2015
© Charles E. Hughes 2000
342
Sorting Algorithms
protected void bubbleSort(int a[]) {
for (int i = a.length; --i >= 0; )
for (int j = 0; j < i; j++) {
if (a[j] > a[j+1]) {
swap(a, j, j + 1);
}
pause();
}
}
protected void quickSort(int a[]) { ... }
7/16/2015
© Charles E. Hughes 2000
343
Run the Sort
protected void initAnimator() {
algName = "BubbleSort";
String at = getParameter("alg");
if (at != null) {
algName = at;
}
setDelay(20);
scramble();
}
protected void algorithm() {
if ("BubbleSort".equals(algName)) {
bubbleSort(arr);
} else if ("QuickSort".equals(algName)) {
quickSort(arr, 0, arr.length - 1);
} else {
bubbleSort(arr);
}
}
7/16/2015
© Charles E. Hughes 2000
344
Separate Algorithms
• Make different algorithms interchangeable
components
• Adding and changing algorithms will have
little impact on the animation mechanism
7/16/2015
© Charles E. Hughes 2000
345
Abstract Algorithm
abstract public class SortAlgorithm {
abstract void sort(int a[]);
private AlgorithmAnimator animator;
protected SortAlgorithm(AlgorithmAnimator anim) {
animator = anim;
}
protected void pause() {
if (animator != null)
animator.pause();
}
protected static void swap(int a[], int i, int j) {
int T;
T = a[i]; a[i] = a[j]; a[j] = T;
}
}
7/16/2015
© Charles E. Hughes 2000
346
Concrete BubbleSort Algorithm
public class BubbleSortAlgorithm extends SortAlgorithm {
public void sort(int a[]) {
for (int i = a.length; --i >= 0; ) {
for (int j = 0; j < i; j++) {
if (a[j] > a[j+1]) {
swap(a, j, j+1);
}
pause();
}
}
}
}
public BubbleSortAlgorithm(AlgorithmAnimator anim) {
super(anim);
}
7/16/2015
© Charles E. Hughes 2000
347
Abstract Factory
public interface AlgorithmFactory {
public SortAlgorithm
makeSortAlgorithm(String algName);
}
7/16/2015
© Charles E. Hughes 2000
348
Concrete Factory
public class StaticAlgoFactory
implements AlgorithmFactory {
public StaticAlgoFactory(AlgorithmAnimator anim) {
animator = anim;
}
public SortAlgorithm makeSortAlgorithm(
String algName) {
if ("BubbleSort".equals(algName)) {
return new BubbleSortAlgorithm(animator);
} else if ("QuickSort".equals(algName)) {
return new QuickSortAlgorithm(animator);
} else {
return new BubbleSortAlgorithm(animator);
}
}
protected AlgorithmAnimator animator;
}
7/16/2015
© Charles E. Hughes 2000
349
Animating Sort 2A
public class Sort2 extends AlgorithmAnimator {
protected SortAlgorithm theAlgorithm;
protected SortAlgorithmFactory algorithmFactory;
protected void initAnimator() {
algName = "BubbleSort";
String at = getParameter("alg");
if (at != null) {
algName = at;
}
algorithmFactory = new StaticAlgoFactory(this);
theAlgorithm =
algorithmFactory.makeSortAlgorithm(algName);
setDelay(20);
scramble();
}
7/16/2015
© Charles E. Hughes 2000
350
Animating Sort 2B
(class Sort2 continued.)
protected void algorithm() {
if (theAlgorithm != null)
theAlgorithm.sort(arr);
}
protected void scramble() {
<same as scramble() in Sort>
}
protected void paintFrame(Graphics g) {
<same as paintFrame() in Sort>
}
}
protected int
arr[];
protected String algName;
7/16/2015
© Charles E. Hughes 2000
351
Display Design 1
Very small interface
public interface SortDisplay {
public void display(int a[], Graphics g,
Dimension d);
}
Minor changes to the main class.
The paintFrame() method becomes:
public void paintFrame(Graphics g) {
theDisplay.display(arr, g, getSize());
}
7/16/2015
© Charles E. Hughes 2000
352
Critique of Display Design 1
Problems:
• Strong coupling between the main class
and the implementations of SortDisplay.
• Limited flexibility.
• What about drawing lines vertically?
• What about drawing lines of 3 pixels wide?
7/16/2015
© Charles E. Hughes 2000
353
Display Design 2
•
Include scramble() in the SortDisplay
public interface SortDisplay {
public void scramble(int a[], Dimension d);
public void display(int a[], Graphics g,
Dimension d);
}
•
The scramble() method in the main class becomes:
void scramble() {
theDisplay.scramble(arr, getSize());
}
7/16/2015
© Charles E. Hughes 2000
354
Critique of Display Design 2
•
•
•
•
The coupling between the main class and
the implementations of SortDisplay is
reduced.
The methods of SortDisplay are not very
cohesive.
Scrambling is quite independent from
displaying.
The only interdependence between the two
methods are --- the array size.
7/16/2015
© Charles E. Hughes 2000
355
Display Design 3
•
The SortDisplay interface
}
•
public interface SortDisplay {
public int getArraySize(Dimension d);
public void display(int a[], Graphics g,
Dimension d);
The scramble() method in the main class becomes:
}
void scramble() {
int n = theDisplay.getArraySize(getSize());
arr = new int[n];
// scramble the numbers in arr[0..(n-1)]
7/16/2015
© Charles E. Hughes 2000
356
Animating Sort 3A
public class Sort3 extends Sort2 {
protected SortDisplay theDisplay;
protected SortDisplayFactory displayFactory;
protected void initAnimator() {
String att = getParameter("dis");
displayFactory =
new StaticSortDisplayFactory();
theDisplay =
displayFactory.makeSortDisplay(att);
super.initAnimator();
}
7/16/2015
© Charles E. Hughes 2000
357
Animating Sort 3B
(class Sort3 continued)
protected void scramble() {
int n = theDisplay.getArraySize(getSize());
arr = new int[n];
for (int i = arr.length; --i >= 0;)
arr[i] = i;
for (int i = arr.length; --i >= 0;) {
int j = (int)(i * Math.random());
SortAlgorithm.swap(arr, i, j);
}
}
}
protected void paintFrame(Graphics g) {
theDisplay.display(arr, g, getSize());
}
7/16/2015
© Charles E. Hughes 2000
358
Sort Display Strategy
7/16/2015
© Charles E. Hughes 2000
359
Exercise #6
• Study the sort applets to see how patterns are used.
Now, add a Merge Sort algorithm to the
StaticAlgoFactory.
• As you become familiar with reflection, you can
change the StaticAlgoFactory to a dynamic one. Keep
this in the back of your mind as you look this example
over.
• Algorithmics challenge – the QuickSort in this
example makes a bad choice of pivot selection. Clean
it up.
7/16/2015
© Charles E. Hughes 2000
360
C++ Indirect Function Calls
• C++ allows you to create pointers to functions, and
then have arrays of such pointers. You then call a
function by dereferencing its pointer.
• Java has no explicit pointer, and thus appears not to
have this capability. However, that’s exactly what we
managed to do with an array of functors – objects
representing functions.
• In fact, Java’s reflection gives you capabilities well
beyond what C++’s indirect calls do. Reflection is the
key.
7/16/2015
© Charles E. Hughes 2000
361
The Collection Framework
7/16/2015
© Charles E. Hughes 2000
362
Kinds of Collections
• Bags – no order; repeats allowed
• Sets – no order; no duplicates
• Lists – sequenced first to last; equality includes
position in sequence as well as value; repeated values
distinguishable by their positions
• Maps – key/value associations (dictionaries); keys are
unique; values can be repeated
7/16/2015
© Charles E. Hughes 2000
363
Collection Matrix
Interface
Implementations
Historical
(legacy)
Set
HashSet
List
TreeSet
ArrayList
LinkedList
Vector
Stack
Map
HashMap
TreeMap
Hashtable
Properties
7/16/2015
© Charles E. Hughes 2000
364
Collection Interface Hierarchy
Collection
List
Set
Map
SortedMap
SortedSet
Notice: Maps are NOT Collections, but they have
various collection views.
7/16/2015
© Charles E. Hughes 2000
365
Collection Interface
Collection
boolean add(Object o)
boolean addAll(Collection c)
void clear()
boolean contains(Object o)
boolean conatinsAll(Collection c)
boolean equals(Object o)
int hashCode()
boolean isEmpty()
Iterator iterator()
boolean remove(Object o)
boolean removeAll(Collection c)
boolean retainAll(Collection c)
int size()
Object[ ] toArray()
Object[ ] toArray(Object[ ] a)
7/16/2015
© Charles E. Hughes 2000
366
Iterator Interface for Collections
Iterator
boolean hasNext()
Object next()
void remove()
7/16/2015
© Charles E. Hughes 2000
367
List Interface
List (extends with new semantics )
boolean add(int i, Object o)
boolean addAll(int i, Collection c)
Object get(int i)
int indexOf(Object o)
int lastIndexOf(Object o)
ListIterator listIterator()
ListIterator listIterator(int i)
boolean remove(int i)
Object set(int i, Object o) // returns old value
List sublist(int i, int j) // i-th to j-th, exlsuive of j-th
7/16/2015
© Charles E. Hughes 2000
368
Iterator Interface for Lists
ListIterator
void add (Object o)
boolean hasNext()
boolean hasPrevious()
Object next()
int nextIndex()
Object previous()
int previousIndex()
void remove()
void set(Object o)
7/16/2015
// adds immediately prior
// replaces last element returned
© Charles E. Hughes 2000
369
Walking a List Backwards
List list = ...;
ListIterator iterator = list.listIterator(list.size());
while (iterator.hasPrevious()) {
Object element = iterator.previous();
// Process element
}
7/16/2015
© Charles E. Hughes 2000
370
Set Interface
Set (just like Collection)
boolean add(Object o)
// must implement correct semantics
boolean addAll(Collection c)
// must implement correct semantics
void clear()
boolean contains(Object o)
boolean containsAll(Collection c)
boolean equals(Object o)
int hashCode()
boolean isEmpty()
Iterator iterator()
boolean remove(Object o)
boolean removeAll(Collection c)
boolean retainAll(Collection c)
int size()
Object[ ] toArray()
Object[ ] toArray(Object[ ] a)
7/16/2015
© Charles E. Hughes 2000
371
SortedSet Interface
SortedSet (extends Set/new semantics )
Comparator comparator()
// null if natural order
Object first()
SortedSet headSet(Object o)
// elements less than o
Object last()
SortedSet subSet(Object o1, Object o2)
SortedSet tailSet(Object o)
7/16/2015
// from o1 up to o2, exclusive
// elements greater than or equal to o
© Charles E. Hughes 2000
372
Comparator Interface
Comparator
int compare(Object o1, Object o2)
// like compareTo
boolean equals(Object o)
// often omitted
// Default comparator of null leads to natural order.
// Natural order is based on compareTo for Comparables
// You must be semantically consistent on concepts of equals.
7/16/2015
© Charles E. Hughes 2000
373
Comparable Interface
Comparable
int compareTo(Object o)
// You must be semantically consistent with equals.
7/16/2015
© Charles E. Hughes 2000
374
Map Interface
Map
void clear()
boolean containsKey(Object key)
boolean containsValue(Object value)
Set entrySet()
// set of map entries
Object get(Object key)
Set KeySet()
int hashCode()
boolean isEmpty()
Object put(Object key, Object value)
void putAll(Map m)
Object remove(Object key)
int size()
Collection values()
// not a set, duplicates can exist
7/16/2015
© Charles E. Hughes 2000
375
Map.Entry Interface
Map.Entry
boolean equals(Object o)
Object getKey()
Object getvalue()
int hashCode()
void setValue(Object value)
// when iterating over pairs, it is safe to use setValue.
// it is not safe to modify the map in any other way while iterating.
// Java 2 is, in general, NOT thread safe.
7/16/2015
© Charles E. Hughes 2000
376
Collection Examples
7/16/2015
© Charles E. Hughes 2000
377
JBuilder3 Execution Log
• Run/Debug tab in Project:Properties
• Set it to Console I/O:Execution Log
7/16/2015
© Charles E. Hughes 2000
378
Map Example #1
import java.util.*;
public class MapExample {
public static void main(String args[]) {
Map map = new HashMap();
Integer ONE = new Integer(1);
for (int i=0, n=args.length; i<n; i++) {
String key = args[i];
Integer frequency = (Integer)map.get(key);
if (frequency == null) frequency = ONE;
else {
int value = frequency.intValue();
frequency = new Integer(value + 1);
}
map.put(key, frequency);
}
System.out.println(map);
Map sortedMap = new TreeMap(map);
System.out.println(sortedMap);
}
}
7/16/2015
© Charles E. Hughes 2000
379
Map Example2
import java.util.*;
import java.io.*;
public class MapExample2 {
public static void main(String args[]) {
Map map = new HashMap();
Integer ONE = new Integer(1);
BufferedReader in;
try {
in = new BufferedReader(new InputStreamReader(
new FileInputStream("Lincoln.txt")));
} catch (FileNotFoundException e) {
in = new BufferedReader(new InputStreamReader(System.in));
}
7/16/2015
© Charles E. Hughes 2000
380
Map Example2 #2
try {
String line;
while ((line = in.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens()) {
String key = st.nextToken().toLowerCase();
Integer frequency = (Integer)map.get(key);
if (frequency == null) frequency = ONE;
else {
int value = frequency.intValue();
frequency = new Integer(value + 1);
}
map.put(key, frequency);
}
}
} catch (IOException e) { }
7/16/2015
© Charles E. Hughes 2000
381
Map Example2 #3
Set set = map.entrySet();
Iterator iter = set.iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String key = (String) entry.getKey();
int count = ((Integer) entry.getValue()).intValue();
System.out.println(key +
(key.length() < 8 ? "\t\t" : "\t") + count);
}
}
}
7/16/2015
© Charles E. Hughes 2000
382
Exercise #7
• Alter MapExample2 so it prints the frequency list
sorted in ascending order by keys.
• Alter MapExample2 so it prints the frequency list
sorted in descending order by keys.
7/16/2015
© Charles E. Hughes 2000
383
Java 2
7/16/2015
© Charles E. Hughes 2000
384
Java 2 – Some Comments
• AWT extended with lightweight Swing components,
supporting a Model/View/Controller paradigm.
• Event model is now delegation, not containment.
• Old trivial collections model of Vector and Stack have
been made industrial strength with Collection
framework.
• Collections and visual Components are no longer
Thread Safe.
7/16/2015
© Charles E. Hughes 2000
385
The Swing GUI Framework
7/16/2015
© Charles E. Hughes 2000
386
Categories of Classes
• GUI Widgets
• Layout Managers
• Events and Event Listeners
7/16/2015
© Charles E. Hughes 2000
387
Heavyweight vs. Lightweight
• AWT widgets are called heavyweight since they have
platform dependent peers.
– This restricts appearance to local platform’s standard way,
reducing portability.
• Swing widgets are lightweight, and exist within what is
usually just a single heavyweight widget.
– Appearance of lightweight widgets is totally controlled by
Java, and is consequently controllable in a platform
independent fashion.
– You can plug in new appearances at will.
7/16/2015
© Charles E. Hughes 2000
388
Swing Heavyweights
• JWindow, JFrame and JDialog are heavywieght Swing
components.
• JDialog is commonly used for simple dialogs, e.g.,
warnings and information.
• JFrame and JWindow are like Frame and Window, but
tailored to hold lightweight components.
7/16/2015
© Charles E. Hughes 2000
389
Swing Lightweight Components
• Java components – it manages contents.
• All have pluggable look and feel.
• setUI(ComponentUI ui) is used
• Don’t have total freedom. For instance, a combo box’s
L&F must implement ComboBoxUI, as well as
ComponentUI
7/16/2015
© Charles E. Hughes 2000
390
Layout Managers
• You can do precise placement in lightweight containers, but it’s
often more convenient to use layout managers, letting them do
placement for you.
• Layout managers are:
– BorderLayout
– BoxLayout
– CardLayout
– FlowLayout
– GridLayout
– GridBagLayout
7/16/2015
© Charles E. Hughes 2000
391
Border Layout Example
import java.awt.*;
import javax.swing.*;
public class Border extends JApplet {
public Border () {
getContentPane().setLayout(new BorderLayout());
getContentPane().add("South", new JButton("South"));
getContentPane().add("North", new JButton("North"));
getContentPane().add("East", new JButton("East"));
getContentPane().add("West", new JButton("West"));
getContentPane().add("Center", new JButton("Center"));
}
}
7/16/2015
© Charles E. Hughes 2000
392
Flow Layout Example
import java.awt.*;
import javax.swing.*;
public class Flow extends JApplet {
public Flow () {
getContentPane().setLayout(new FlowLayout());
getContentPane().add(new JButton("Java"));
getContentPane().add(new JButton("C++"));
getContentPane().add(new JButton("Perl"));
getContentPane().add(new JButton("Ada"));
getContentPane().add(new JButton("Smalltalk"));
getContentPane().add(new JButton("Eiffel"));
}
}
7/16/2015
© Charles E. Hughes 2000
393
Grid Layout Example
import java.awt.*;
import java.applet.Applet;
import javax.swing.*;
public class Grid extends JApplet {
public void init () {
int row = 0, col = 0;
String att = getParameter("row");
if (att != null) row = Integer.parseInt(att);
att = getParameter("col");
if (att != null) col = Integer.parseInt(att);
if (row == 0 && col == 0) {row = 3; col = 2;}
getContentPane().setLayout(new GridLayout(row, col));
getContentPane().add(new JButton("Java"));
getContentPane().add(new JButton("C++"));
getContentPane().add(new JButton("Perl"));
getContentPane().add(new JButton("Ada"));
getContentPane().add(new JButton("Smalltalk"));
getContentPane().add(new JButton("Eiffel"));
}
}
7/16/2015
© Charles E. Hughes 2000
394
Nested Panel Layout Example
import java.awt.*;
import javax.swing.*;
public class NestedPanels extends JApplet {
public NestedPanels () {
ContentPane cp = getContextPane();
JPanel center = new JPanel(); center.setLayout(new BorderLayout());
center.add("South", new JButton("south")); center.add("North", new JButton("north"));
center.add("East", new JButton("east")); center.add("West", new JButton("west"));
center.add("Center", new JButton("center"));
JPanel south = new JPanel(); south.setLayout(new FlowLayout());
south.add(new JButton("Help"));
choice = new Choice();
choice.addItem("one"); choice.addItem("two"); choice.addItem("three");
choice.addItem("four"); choice.addItem("five");
south.add(choice);
messageBar = new JLabel("This is a message bar.");
south.add(messageBar);
cp.setLayout(new BorderLayout());
cp.add("North", new JButton("North")); cp.add("East", new JButton("East"));
cp.add("West", new JButton("West"));
cp.add("South", south); cp.add("Center", center);
}
protected JLabel messageBar; protected Choice choice;
}
7/16/2015
© Charles E. Hughes 2000
395
Why a Context Pane in JApplet?
• In applets, you add widgets directly to the Applet
since it is a subclass of Panel, a heavyweight
Container.
• Even though JApplet is a subclass of Applet, the
Panel is not used for Components (widgets). The
JApplet includes a RootPane, which in turn contains a
ContentPane and a GlassPane. The ContentPane is
where you add widgets. That’s also where you set the
layout.
7/16/2015
© Charles E. Hughes 2000
396
Containment versus Delegation
• The old event model is based on containment – events
not totally handled in one component are passed to
the container component.
– This restricts the way events are propagated.
– This leads to switch style programming.
• The new event model is based on delegation of event
handling to objects who registered interest (listeners).
– This means listeners plug in to event producers.
– This supports the Model-View-Controller paradigm.
7/16/2015
© Charles E. Hughes 2000
397
Adding Event Handling #1
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class NestedPanels2 extends NestedPanels
implements ActionListener, ItemListener {
public NestedPanels2() {
super();
choice.addItemListener(this);
beActionListener(getContentPane());
}
7/16/2015
© Charles E. Hughes 2000
398
Adding Event Handling #2
public void itemStateChanged(ItemEvent event) {
if (event!=null)
System.out.println("ItemStateChanged: " + event);
Choice choice = (Choice) event.getSource();
if (choice != null)
messageBar.setText("Choice selected: " + event.getItem());
}
public void actionPerformed(ActionEvent event) {
if (event!=null)
System.out.println("ActionPerformed: " + event);
JButton source = (JButton) event.getSource();
if (source != null)
messageBar.setText("Button pushed: " + source.getText());
}
7/16/2015
© Charles E. Hughes 2000
399
Adding Event Handling #3
protected void beActionListener(Component comp) {
if (comp != null) {
if (comp instanceof JButton) {
JButton button = (JButton) comp;
button.addActionListener(this);
} else if (comp instanceof Container) {
Container container = (Container) comp;
int n = container.getComponentCount();
for (int i = 0; i < n; i++)
beActionListener(container.getComponent(i));
}
}
}
}
7/16/2015
© Charles E. Hughes 2000
400
Adding Event Handling #1
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class NestedPanels2 extends NestedPanels
implements ActionListener, ItemListener {
public NestedPanels2() {
super();
choice.addItemListener(this);
beActionListener(getContentPane());
}
7/16/2015
© Charles E. Hughes 2000
401
The MVC Paradigm
• The core of an application or any part of an
application is a model which maintains the state of the
world (or piece of the worlds).
• A view is a user perception of the state of a model.
Often, we want multiple views of the same model.
• A controller is how a user interacts with the model,
typically through some view.
7/16/2015
© Charles E. Hughes 2000
402
ST-80 Lap Timer Class
Model subclass: #LapTimer
instanceVariableNames: 'lapStart '
classVariableNames: ''
poolDictionaries: ''
category: 'LapTimer'
“=============CLASS METHODS============”
open
"LapTimer open"
| lapTimer topView |
lapTimer := LapTimer new reset.
topView := LapTimerView lapTimer: lapTimer.
topView controller open.
^lapTimer
7/16/2015
© Charles E. Hughes 2000
403
Lap Timer Instance Methods
“=============INSTANCE METHODS============”
contents
"Answer the text for the lap time."
| interval |
interval := (Time now subtractTime: lapStart)
intervalString.
interval = '' ifTrue: [
interval := 'no time has passed' ].
^ interval
lap
self changed
reset
lapStart := Time now.
self lap
7/16/2015
© Charles E. Hughes 2000
404
Lap Timer View #1
StandardSystemView subclass: #LapTimerView
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'LapTimer'
“=============CLASS METHODS============”
lapTimer: aLapTimer
"subviews, timer, reset and lap button."
| lapTimerView timerView resetView lapView |
lapTimerView := self new model: aLapTimer;
label: 'Lap Timer'.
timerView := StringHolderView new
borderWidth: 2; window: (0 @ 0 extent: 100 @ 100);
backgroundColor: Color yellow;
model: aLapTimer;
controller: NoController new.
7/16/2015
© Charles E. Hughes 2000
405
Lap Timer View #2
resetView := SwitchView new
borderWidth: 2; label: 'RESET' asParagraph;
window: (0 @ 0 extent: 50 @ 100); backgroundColor:
Color red;
model: (Button new onAction: [ aLapTimer reset] ).
lapView := SwitchView new
borderWidth: 2; label: 'LAP' asParagraph;
window: (0 @ 0 extent: 50 @ 100);
backgroundColor: Color green;
model: (Button new onAction: [ aLapTimer lap] ).
lapTimerView addSubView: timerView.
lapTimerView addSubView: resetView below: timerView.
lapTimerView addSubView: lapView toRightOf: resetView.
^lapTimerView
7/16/2015
© Charles E. Hughes 2000
406
Swing’s MVC
• Really M(VC) in that views and controllers are paired.
• Even a button has a model, its state; a view, its
appearance; and controller to sense mouse activity in
the button’s region.
• A table has a model which contains its state, and
hence provides contents to the table’s cells.
7/16/2015
© Charles E. Hughes 2000
407
Lots of Swing Examples
7/16/2015
© Charles E. Hughes 2000
408
Examples from Swing Tutorial
•
•
•
•
•
•
•
•
•
•
•
Label
Button
RadioButtons
CheckBox
ComboBox
SplitPane
LayeredPanel
TextField
Password
List
InternalFrame
7/16/2015
© Charles E. Hughes 2000
409
More Swing Examples
• Label
• ColorChooser
– BorderFactory is a Factory pattern
• Observe how borders adapt to Component colors
• ColorChooser2
– Note use of Modal Dialog for ColorChooser
• ComboBoxDemo2
– Use of Formatter
• CustomComboBox
– Use of renderer
7/16/2015
© Charles E. Hughes 2000
410
Even More Swing Examples
• Dialog
• DynamicTree
• FileChooser
• List
• ListDialog
• Menu
– Use of Box in Glue
• PopupMenu
– Adding listener to multiple components
7/16/2015
© Charles E. Hughes 2000
411
What, More Swing Examples?
• TabbedPanel
– Explicit request to not be double buffered
• SimpleTable
– Note data and column names are passed in constructor
• SimpleTableSelection
• Table
– Providing a model
– Follow the firing of an event
• Floyd’s and Warshall’s algorithms
– Works but is rather unaesthetic and unadaptable
7/16/2015
© Charles E. Hughes 2000
412
Exercise #8
• Clean up my student’s Floyd’s algorithm program.
Make it layout better. Add scroll bars. Make button
prettier. Let graph be editable, and when edited the
result tables go back to an “original” state.
• You may want to change resize behavior if paths get
long.
• What about allowing longer tables? Fields to
dynamically resize?
7/16/2015
© Charles E. Hughes 2000
413
An Excursion through LAF
• Create an applet and try different Look and Feels.
7/16/2015
© Charles E. Hughes 2000
414
Java I/O
7/16/2015
© Charles E. Hughes 2000
415
The I/O Framework
Java supports two types of IO:
• Stream IO
•
•
•
•
A stream is a sequence of bytes.
Stream-based IO supports reading or writing data
sequentially.
A stream may be opened for reading or writing, but not
reading and writing.
There are tow types of streams: the byte streams and the
character stream.
•
Random access IO
•
Random access IO support reading and writing data at
any positions of a file. A random access file may be
opened for reading and writing.
7/16/2015
© Charles E. Hughes 2000
416
Byte Streams
7/16/2015
© Charles E. Hughes 2000
417
Character Streams
7/16/2015
© Charles E. Hughes 2000
418
Standard I/O Streams
public class java.lang.System {
public static final InputStream in;
public static final PrintStream out;
public static final PrintStream err;
//...
}
7/16/2015
© Charles E. Hughes 2000
419
Using Reader and Writer
BufferedReader file_in
= new BufferedReader(
new FileReader("foo.in"));
BufferedReader in
= new BufferedReader(
new InputStreamReader(System.in));
PrintWriter file_out
= new PrintWriter(
new BufferedWriter(
new FileWriter("foo.out")));
Writer out
= new BufferedWriter(
new OutputStreamWriter(System.out));
7/16/2015
© Charles E. Hughes 2000
420
By default, the character encoding is specified by the system
property;
file.encoding=8859_1
You can use other encoding by doing the following
BufferedReader file_in =
new BufferedReader(
new InputStreamReader(
new FileInputStream("foo.in"), "GB2312"));
PrintWriter file_out =
new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream("foo.out", "GB2312"))));
7/16/2015
© Charles E. Hughes 2000
421
Console Input/Output in Java
KB Input / Output in Java
import java.io.* // needed to get access to I/O
//Output
System.out.print(aString);
System.out.println(aString);
//Input (one value per line / later we’ll do better)
BufferedReader stdin =
new BufferedReader(new InputStreamReader(System.in));
int anInt1 = Integer.parseInt(stdin.readLine()); // one way
int anInt2 = Integer.valueOf(stdin.readLine()).intValue(); //2nd way
double aDouble =
Double.valueOf(stdin.readLine()).doubleValue();
Integer is a class, each of whose instances holds a single int
Double is a class, each of whose instances holds a single double
7/16/2015
© Charles E. Hughes 2000
422
Java2D
• Large Example Set
• Amazing Stuff
7/16/2015
© Charles E. Hughes 2000
423
Postscript Reader
• Just a nice example
7/16/2015
© Charles E. Hughes 2000
424
Applet to Applet Communication
7/16/2015
© Charles E. Hughes 2000
425
Inter-Applet Communication
• We can have multiple applets on a page talking to
each other
• Restrictions
– Applets have to come from the same server
– Many browsers require that the applets come from the same
code base (directory)
– They must be running on the same page
– Applets must be named
7/16/2015
© Charles E. Hughes 2000
426
HTML Requirements
• By default, applets are unnamed
• The name must be specified in the HTML
• Name should be case insensitive
• By specifying a NAME attribute within the applet's <APPLET> tag.
<APPLET CODEBASE=project2/ CODE=CannonUI.class WIDTH=450
HEIGHT=200 NAME=”User Interface">
• By specifying a NAME parameter with a <PARAM> tag.
<APPLET CODEBASE=project2/ CODE=cannon.class WIDTH=450
HEIGHT=300> <PARAM NAME="name" value=”Simulator">
7/16/2015
© Charles E. Hughes 2000
427
Sending a Message
//get the name of the receiver
nameField = getParameter(”SIMNAME");
Applet simulator = null;
String simName = nameField.getText();
//look it up
simulator = getAppletContext().getApplet(simName);
//Check to make sure it is right
if (simulator != null) {
if (!(simulator instanceof cannonSim)) {
//found the right name, but it a wrong type
} else {
//do what we want to do
//cast it to the right type and send a message
((cannonSim) simulator ).processRequestFrom(
“Contents of Message”);
//Actually, you are invoking a method
}
} else {
//no applets by that name found
7/16/2015
© Charles E. Hughes 2000
428
Receiving a Message
• Requires a method to catch and parse the message
public void processRequestFrom(String message) {
System.out.println(
“I wrote all this code and this is what was sent “
+ message);
}
• For bi-directional communications, have the sender
send a reference to itself
– ((Receiver) receiver.replyTo(this);
7/16/2015
© Charles E. Hughes 2000
429
Receiving a Message
• You can only find the applets that came from the same
server
public void listApplets() {
//Enumeration will contain all
//applets on this page (including
//this one) that we can send messages to.
Enumeration all =
getAppletContext().getApplets();
while (all.hasMoreElements()) {
Applet applet =
(Applet) all.nextElement();
//do something clever
}
}
7/16/2015
© Charles E. Hughes 2000
430
Monitor Server #1
import
import
import
import
javax.swing.*;
java.awt.*;
java.awt.event.*;
java.util.Enumeration;
public class Monitor extends JApplet
implements ActionListener {
private final int maxTemperature = 100;
private final int minTemperature = 0;
private int temperature = 50;
private Label label =
new Label("Current Temperature = " +
String.valueOf(temperature), Label.RIGHT);
7/16/2015
© Charles E. Hughes 2000
431
Monitor Server #2
public void init() {
Button button = new Button("Update Display");
getContentPane().add(label);
getContentPane().add(button);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent event) {
label.setText("Current Temperature = " +
String.valueOf(temperature));
}
7/16/2015
© Charles E. Hughes 2000
432
Monitor Server #3
public synchronized void increment() {
temperature++;
if (temperature > maxTemperature) {
Enumeration e=getAppletContext().getApplets();
while (e.hasMoreElements()) {
Applet applet = (Applet)e.nextElement();
if (applet instanceof Incrementer) {
((Changer)applet).slowDown();
}
else if (applet instanceof Decrementer) {
((Changer)applet).speedUp();
}
}
}
}
7/16/2015
© Charles E. Hughes 2000
433
Monitor Server #4
public synchronized void decrement() {
temperature--;
if (temperature < minTemperature) {
Enumeration e=getAppletContext().getApplets();
while (e.hasMoreElements()) {
Applet applet = (Applet)e.nextElement();
if (applet instanceof Decrementer) {
((Changer)applet).slowDown();
}
else if (applet instanceof Incrementer) {
((Changer)applet).speedUp();
}
}
}
}
7/16/2015
© Charles E. Hughes 2000
434
Monitor Server #5
public void paint(Graphics g) {
g.drawRect(0, 0,
getSize().width-1, getSize().height-1);
}
public String getAppletInfo() {
return "Monitor by Charles E. Hughes";
}
}
7/16/2015
© Charles E. Hughes 2000
435
Changer Client Abstraction #1
import
import
import
import
javax.swing.*;
java.awt.*;
java.awt.event.*;
java.util.Enumeration;
abstract public class Changer extends JApplet
implements Runnable {
private final int minDelay = 10;
private final int maxDelay = 100;
private final int delayChange = 2;
private int delay = 50;
protected Monitor monitor = null;
private Thread thread = null;
private Label label = new Label("Current Delay = “
+ String.valueOf(delay), Label.RIGHT);
7/16/2015
© Charles E. Hughes 2000
436
Changer Client Abstraction #2
public void init() {
getContentPane().add(label);
Enumeration e = getAppletContext().getApplets();
while (e.hasMoreElements()) {
Applet applet = (Applet)e.nextElement();
if (applet instanceof Monitor) {
monitor = (Monitor) applet;
}
}
}
public void displayDelay() {
label.setText("Current Delay = " +
String.valueOf(delay));
}
7/16/2015
© Charles E. Hughes 2000
437
Changer Client Abstraction #3
public synchronized void slowDown() {
if (delay < maxDelay) {
delay += delayChange; displayDelay();
}
}
public synchronized void speedUp() {
if (delay > minDelay) {
delay -= delayChange; displayDelay();
}
}
abstract public void action();
public void paint(Graphics g) {
g.drawRect(0, 0,
getSize().width - 1, getSize().height - 1);
}
7/16/2015
© Charles E. Hughes 2000
438
Changer Client Abstraction #1
public void start() {
if ((thread == null) && (monitor != null)) {
thread = new Thread(this); thread.start();
}
validate();
}
public void stop() {
thread = null;
}
7/16/2015
© Charles E. Hughes 2000
439
Changer Client Abstraction #1
public void run() {
while (thread != null) {
try {Thread.sleep((int)(delay*Math.random()));
} catch (InterruptedException e){}
action();
}
}
public String getAppletInfo() {
return "Changer by Charles E. Hughes";
}
}
7/16/2015
© Charles E. Hughes 2000
440
Changer Client Abstraction #1
import
import
import
import
javax.swing.*;
java.awt.*;
java.awt.event.*;
java.util.Enumeration;
public class Incrementer extends Changer {
public void action() {
monitor.increment();
}
}
7/16/2015
© Charles E. Hughes 2000
441
Changer Client Abstraction #1
import
import
import
import
javax.swing.*;
java.awt.*;
java.awt.event.*;
java.util.Enumeration;
public class Decrementer extends Changer {
public void action() {
monitor.decrement();
}
}
7/16/2015
© Charles E. Hughes 2000
442
Java-Based Distributed Models
7/16/2015
© Charles E. Hughes 2000
443
What Is Distributed Computing?
• Multiple heterogeneous devices at multiple sites
– Each operates independently with local resource controls
• Multi-purpose interconnection network
• Shared purpose
7/16/2015
© Charles E. Hughes 2000
444
What Is Parallel Computing?
• Multiple, usually similar, devices at a single site
– Some, perhaps all, resources are centrally controlled
• Dedicated interconnection network
• Shared purpose
7/16/2015
© Charles E. Hughes 2000
445
Quick Comparison
• Parallel Computing
– High bandwidth; Low latency; Inflexible communication
• Distributed Computing
– Varied bandwidth; Often high latency; Flexible communication
– Requires more attention to reliability, security and routing
7/16/2015
© Charles E. Hughes 2000
446
Consequences of DS
• Want algorithms based on loosely coupled designs
• Communication protocol is basis for coordination
• Enforce order only when required
– Typically by problem semantics
7/16/2015
© Charles E. Hughes 2000
447
Common DS Paradigms
•
Channels – send / receive
– Messages to single or collection of recipients
•
Distributed Objects – invoke services on remote objects
– Requires objects to be transferred over network
• Serialization / un-serialization
•
Tuple space (shared memory) – write, read, take
– A space for reliable communication and coordination
7/16/2015
© Charles E. Hughes 2000
448
Challenges of DS
• Independence and Non-Homogeneity of Nodes
• Communication is Plagued by Issues of
– Reliability
– Security
– Speed
7/16/2015
© Charles E. Hughes 2000
449
Benefits of Distributed Systems
• Can evolve with new resources and paradigms
– Not costly to upgrade
– Not tied to one communication/coordination paradigm
• Can scale to existing resources
– Add another computer; Get another node
7/16/2015
© Charles E. Hughes 2000
450
Common DS Paradigms
•
Channels – send / receive
– Messages to single or collection of recipients
•
Distributed Objects – invoke services on remote objects
– Requires object serialization and un-serialization
•
Tuple space – write, read, take
– A space for reliable communication and coordination
7/16/2015
© Charles E. Hughes 2000
451
IP Network Communication
• Each node has an address (IP address)
• Each node has many mailboxes (ports)
• Messages (packets) are received at and sent through
ports
7/16/2015
© Charles E. Hughes 2000
452
UDP – Simplest Communication
• Like regular mail
– I send messages with a return address and mailbox #
• There’s no guarantee of delivery or order of receipt
– If all goes well you receive my mail at your mailbox
• You can respond using my address and mailbox number
7/16/2015
© Charles E. Hughes 2000
453
Sample UDP Service
• CLIENT (sender)
socket = new DatagramSocket();
packet = new DatagramPacket(sendBuf,256,host,5500);
socket.send(packet);
• SERVER (receiver)
socket = new DatagramSocket(5500);
packet = new DatagramPacket(buf, 256);
socket.receive(packet);
address = packet.getAddress();
port = packet.getPort();
s = new String(packet.getData(),packet.getlength());
7/16/2015
© Charles E. Hughes 2000
454
TCP/IP – Common Protocol
• Like a phone call
– I place a call your address and ask for you (port)
– You pick up and automatically have my address and port
– We have a two-way channel (stream) over which we communicate
– We need to be sure our messages are arriving reliably and in order
7/16/2015
© Charles E. Hughes 2000
455
Sample TCP/IP Service
• CLIENT (sender, then just participant)
connection = new Socket( host, 5000 );
in = connection.getInputStream();
out = connection.getOutputStream();
• SERVER (receiver, then just participant)
server = new ServerSocket( 5000, 2 );
connection = server.accept();
in = connection.getInputStream();
out = connection.getOutputStream();
7/16/2015
© Charles E. Hughes 2000
456
Examples
• Datagram visitor counter
• TCP/IP visitor counter
• Networked Hangman
7/16/2015
© Charles E. Hughes 2000
457
Distributed Objects #1
Steps for Distributed Objects:
Creating a service:
Compile code producing
skeleton (server side) and stub (client side)
Note: Usually involves IDL (Interface Definition Language)
Server action:
Register service with Object Manager
(sometimes just registry on server)
Note: Object manager is often called an ORB
(object request broker)
Client action:
Request service from Object Manager
Note: This usually involves a Name Server
7/16/2015
© Charles E. Hughes 2000
458
Distributed Objects #2
Object manager action:
Negotiate with service providers for an object
Note: This sometimes involves Reflection
Deliver remote object to client
Client/Server Interaction:
Client uses remote object to get services
Server receives remote messages, provides results
Arguments and results can be
by-value (local copy) or
by reference (remote handle)
This exchange involves serializing/unserializing objects
Note: Serializing is sometimes called marshalling
Roles are reversed when server sends messages to remote
objects from client
7/16/2015
© Charles E. Hughes 2000
459
Java Distributed Objects (RMI)
RMI IDL is Java Interface; rmic compiles skeleton and stub
Write interface which must extend Remote interface
Generate skeleton and stubs
Server Application:
Write service implementation corresponding to interface
Server registers a service by name on some RMI port
Server must start an RMI registry prior to this
Note: default port is 1099
Client Applet:
Write client applet
Client "looks up" service
Note: Need server IP address, port, and name of service
Lookup returns remote object
Note: Class of remote object is name of Interface (stub)
7/16/2015
© Charles E. Hughes 2000
460
Remote Messages
• Personalized at the object level
• Messages are at a high-level of abstraction
• Interpretation of messages is at receiver end
7/16/2015
© Charles E. Hughes 2000
461
Sketch of Sample RMI Service
• INTERFACE
public interface Hughes extends Remote {
ResType service() throws RemoteException;}
• CLIENT
obj = (Hughes)Naming.lookup(“//host/CharlesServer”);
result = obj.service();
• SERVER
obj = new HughesImpl();
Naming.rebind("//host/CharlesServer", obj);
7/16/2015
© Charles E. Hughes 2000
462
Tuple Space
• Tuples are like entries in a database
– < “Mexico City”, “Querétaro”, 180 >
means it takes 180 min. to travel from Mexico City to Querétaro
• We can match this with many templates
– < “Mexico City”, “Querétaro”, Integer >
– < String, “Querétaro” , 180 >
7/16/2015
© Charles E. Hughes 2000
463
Tuple Match
• Template is of a chosen class
• Template fields can have values or null
• Template can match only tuples of class or subclass
• Values are exact matches; nulls are type matches
7/16/2015
© Charles E. Hughes 2000
464
Sketch of JavaSpace Service
• TEMPLATE
public class Atlas implements Entry {
public String startCity;
public String endCity;
public Integer travelTime; }
• PRODUCER
JavaSpace space = SpaceAccessor.getSpace();
Atlas msg = new Atlas(“Mexico City", “Querétaro”, 180);
space.write(msg, null, Lease.FOREVER);
• CONSUMER
JavaSpace space = SpaceAccessor.getSpace();
Atlas template = new Atlas(); endCity = “Querétaro”;
Atlas msg = space.take(template, null, Long.MAX_VALUE);
7/16/2015
© Charles E. Hughes 2000
465
Tuple Space Bid for Airline Ticket
•
Customer write bid to proxy’s tuple space
– p.write<me, home, to, leave, return, bid>
•
Customer takes bids from tuple space
– p.take<?airline, me, home, to, ?leave, ?return, ?price>
•
Customer accepts some bid
– p. write<airline,me,home,to,leave,return,price,credit>
7/16/2015
© Charles E. Hughes 2000
466
Proxy to Airlines
•
Proxy takes bid from tuple space
– p.take<?you, ?home, ?to, ?leave, ?return, ?bid>
•
Proxy replicates (writes) bid to each airline (a)
– a.write<airline, you, home, to, leave, return, bid>
•
Proxy awaits and relays prices to you
– a.read<?airline, you, home, to, leave, return, price>
– p.write<airline, you, home, to, leave, return, price>
7/16/2015
© Charles E. Hughes 2000
467
Completing the Purchase
• Proxy passes your acceptance on
• Airline sends confirmation which is relayed to you
• Uses multiple tuple spaces
• Uses class (type) of template as part of match
7/16/2015
© Charles E. Hughes 2000
468
Atomic Operations
• Want to treat group of actions as atomic
• At some point we either
– Commit and roll all changes into visible state; or
– Abort and roll back state to condition before group
7/16/2015
© Charles E. Hughes 2000
469
Transactions
• Some client starts a transaction
• Others join the transaction
• Client asks for a vote from participants
• Each responds prepared, nochanges, or abort
7/16/2015
© Charles E. Hughes 2000
470
Leases
• Crashes could be real bad with deserted tuples
• Each tuple leases space
– You must renew lease or tuple is deleted automatically
7/16/2015
© Charles E. Hughes 2000
471
Completing Transactions
• All participants keep state at start
• All prepared participants save prepared state
• Client reports roll back if anyone voted abort
• Client reports roll forward if no aborts
– Nochanges do not participate, but should pause
7/16/2015
© Charles E. Hughes 2000
472
Jini Architecture
• Discovery
– Find Jini lookup service (acts as broker)
• Join (if providing new service)
• Lookup services (if required)
7/16/2015
© Charles E. Hughes 2000
473
Discovery Parameters
• Protocol version number ( = 1 )
• Response port
• Groups to discover (or empty for all)
• Set of lookup services that already responded
• All packed into at most 512 bytes for single UDP packet
7/16/2015
© Charles E. Hughes 2000
474
Discovery Process
Multicast request
client
Multicast request
server
Multicast response
server
Multicast response
client
Discovering Entity
Lookup Service
7/16/2015
© Charles E. Hughes 2000
475
Discovery Protocol
• Use multicast to request local lookup service
• Use unicast to request specific lookup service
7/16/2015
© Charles E. Hughes 2000
476
Join Parameters
• Service ID – assigned when service is new
• Attributes that describe service
• Groups in which service participates
• Lookup services at which this is (to be) registered
7/16/2015
© Charles E. Hughes 2000
477
Avoiding a Packet Storm
• Wait a random time (up to 15 seconds)
• Then register service at lookup sites
• Random wait is useful after a crash
• If didn’t do this, then all servers would start simultaneously
– Technique similar to that used after Ethernet collision
7/16/2015
© Charles E. Hughes 2000
478
Lookup
• Use lookup service to get desired service
– Can choose by group and attributes
• Print service that prints in color at 1440 dpi
• Three-D rendering object that imports VRML
• Service object can be remote or a local proxy
7/16/2015
© Charles E. Hughes 2000
479
What About Distributed GC?
• Thought Problem
7/16/2015
© Charles E. Hughes 2000
480
More on ORBs and Persistency
7/16/2015
© Charles E. Hughes 2000
481
CORBA
• Developed by OMG
• Key is ORB (Object Request Broker)
– Client can invoke services from server
– Language and platform are not issues
– Object provided contract is all that matters
• Contacts are provide through IDL
– Interface definition language
7/16/2015
© Charles E. Hughes 2000
482
Legacy Objects
• New objects are described by IDL
– Implemented in OO languages (Java, C++)
• Legacy applications are wrapped
– IDL gives interface to wrapper object
– Wrapper acts as buffer and translator
– Users do not know it’s legacy
– Can eventually swap out the old with no disruption in service
7/16/2015
© Charles E. Hughes 2000
483
XML
• Document Type Definition (DTD)
– What are valid tags?
• eXtensible Markup Language
– How are documents marked up?
• eXtensible Linking Language
– How are documents linked?
• eXtensible Style Language
– How do documents appear when displayed?
7/16/2015
© Charles E. Hughes 2000
484
HTML
• A small subset of XML
– Really of XML’s parent, SGML
• DTD defined by browser community
• Even style is embedded in browser
7/16/2015
© Charles E. Hughes 2000
485
My Credit Card Statement
• First USA switched to XML
– Old way of using Quicken gone
– Need new Quicken
– Well, they backed off
• Benefit to bank
– XML is readable as text
– Standard format for any statement reader
7/16/2015
© Charles E. Hughes 2000
486
A Credit Card Report
OFXHEADER:100
DATA:OFXSGML
VERSION:102
SECURITY:NONE
ENCODING:USASCII
CHARSET:1252
COMPRESSION:NONE
OLDFILEUID:NONE
NEWFILEUID:NONE
<OFX>
…
actual data here
</OFX>
7/16/2015
© Charles E. Hughes 2000
487
Transaction Sign On
<SIGNONMSGSRSV1>
<SONRS>
<STATUS>
<CODE>0
<SEVERITY>INFO
</STATUS>
<DTSERVER>19991220050007[0:GMT]
<LANGUAGE>ENG
<FI>
<ORG>Bank One
<FID>3450
</FI>
<INTU.BID>3450
</SONRS>
</SIGNONMSGSRSV1>
7/16/2015
© Charles E. Hughes 2000
488
Customer and Transactions
…
<CREDITCARDMSGSRSV1>
<CCSTMTTRNRS>
<TRNUID>0
<STATUS>
<CODE>0
<SEVERITY>INFO
</STATUS>
<CCSTMTRS>
<CURDEF>USD
<CCACCTFROM>
<ACCTID>XXXXXXXXXXXXXXXX
</CCACCTFROM>
here’s where transactions come
</CCSTMTRS>
</CCSTMTTRNRS>
</CREDITCARDMSGSRSV1>
7/16/2015
© Charles E. Hughes 2000
489
An Actual Transaction
<BANKTRANLIST>
<DTSTART>19990904120000[0:GMT]
<DTEND>19991220120000[0:GMT]
<STMTTRN>
<TRNTYPE>DEBIT
<DTPOSTED>19991204120000[0:GMT]
<DTUSER>19991204120000[0:GMT]
<TRNAMT>-32.68
<FITID>199912042410838AK8ADB07WH
<REFNUM>2410838AK8ADB07WH
<NAME>BOSTONS FISH HOUSE INC
<MEMO>Sale
</STMTTRN>
</BANKTRANLIST>
7/16/2015
© Charles E. Hughes 2000
490
Java and XML
• Protocol Specific Object Model
– Associates a given protocol with Java objects
7/16/2015
© Charles E. Hughes 2000
491
Persistency & Networking
• Preparing an object
• Presently requires serialization
– Makes data into binary stream
– Must unserialize at other end
– Changes in class design can make objects unreadable
• Maybe better to store in XML
– DTD can be used to decode
7/16/2015
© Charles E. Hughes 2000
492
Data Mining and XML
• Use DTD to interpret archives
• Use lightweight agents to mine
– Opportunistic and intelligent
– Data vaults contains information
• Not just data
• Can fish out my habits
– Okay, so it’s a bad pun on the restaurant
7/16/2015
© Charles E. Hughes 2000
493
Java Beans
7/16/2015
© Charles E. Hughes 2000
494
What is a Bean?
• A Bean is a language supported component
– it is a discrete, easily reusable component
– it abides by a well defined interface
• It can be manipulated visually using a visual application builder
tool
– Normally, it is a visual component (widget)
– It can also be a non-graphical component
• It can store and retrieve its state
– Persistence is achieved via serialization
• It has a built-in discovery mechanism
– Allows for dynamic interactions
• Its methods are no different than any other Java methods
– By default all public methods are exported.
7/16/2015
© Charles E. Hughes 2000
495
Why Beans?
• Beans expose their features to builder tools for visual
manipulation.
– Feature names adhere to specific design patterns
– The tool can then examine the Bean's patterns, discern its features,
and expose those features for visual manipulation.
• Beans are maintained in a palette or toolbox.
• You can select a Bean from the toolbox, drop it into a form,
modify its appearance and behavior, define its interaction with
other Beans, and compose it and other Beans into an applet,
application, or new Bean.
• All this can be done without writing a line of code.
7/16/2015
© Charles E. Hughes 2000
496
The Bean Box Interface
7/16/2015
© Charles E. Hughes 2000
497
Introspection
• Builder tools discover a Bean's features by a process known as
introspection.
• Beans support introspection in two ways:
– Adhering to specific design patterns when naming Bean features.
• The java.beans.Introspector class examines Beans for these design
patterns to discover Bean features.
• The Introspector class relies on the core reflection API.
– Explicitly providing property, method, and event information with a
related Bean Information class.
• A Bean information class implements the BeanInfo interface.
• A BeanInfo class explicitly lists those Bean features that are to be
exposed to application builder tools.
7/16/2015
© Charles E. Hughes 2000
498
Properties
• Properties are a Bean's appearance and behavior characteristics
that can be changed at design time.
• Builder tools use introspection on a Bean to discover its
properties, and expose those properties for manipulation.
• Simple Properties
– aspects of a Bean's appearance and behavior that are changeable at
design time
• Bound Properties
– when their value changes, provide event notification to other objects.
• Constrained Properties
– proposed property changes can be okayed or vetoed by other
objects.
• Indexed Properties
– multiple-value properties.
7/16/2015
© Charles E. Hughes 2000
499
Customization
• Beans expose properties so they can be customized
at design time.
• Customization is supported in two ways
– By using property editor
– by using more sophisticated
Bean customizers.
7/16/2015
© Charles E. Hughes 2000
500
Communication via Events
• Beans use events to communicate with other Beans.
– Similar concept to Swing
• A Bean that wants to receive events (a listener Bean)
registers its interest with the Bean that fires the event
(a source Bean).
• Builder tools can examine a Bean and determine
which events that Bean can fire (send) and which it
can handle (receive).
7/16/2015
© Charles E. Hughes 2000
501
Bean Persistence
• Persistence enables Beans to save and restore their
state.
• Once you've changed a Beans properties, you can
save the state of the Bean and restore that Bean at a
later time, property changes intact.
• JavaBeans uses Java Object Serialization to support
persistence.
7/16/2015
© Charles E. Hughes 2000
502