Page 1
Languages and Tools for Object-Oriented
Development & Object-Oriented Analysis
and Design –
Verified Software Systems
Rainer Marrone based on slides of
Prof. Dr. J.W. Schmidt
Dr. Hans-Werner Sehring
Software Systems Institute (STS)
Harburger Schlossstraße 20
21071 Hamburg
http://www.sts.tu-harburg.de/teaching/
Page 2
LTOOD/OOAD – Verified Software Systems 2
Software Development Today
o in teams
o by tool support
o under reuse of previous investments
o with change management in mind
Page 3
LTOOD/OOAD – Verified Software Systems 3
Course Concept
*Cases, Lessons learnt, Principles, Risks, ... Pragmatics
(“how to ...”)
**
Eclipse©, various
development tools
Together©,
(Word©),
Libraries, ...
Word©, Pen &
Paper, Knowledge
Mgmt., (Together©)
Tools
(overview, use,
interop., ...)
*(*)*
Formal Language
PL Code (Java©,
SQL, …)
(Semi-)Formal
Language
Diagrams (UML)
Natural Language
Texts, (Diagrams)
Languages
(Syntax,
Semantics)
**
Structured Code:
- Classes
- Modules
- Relations, ...
Graphs, Nets:
- ER
- Activities
- Sequences, ...
Interviews:
- Goals
- Resources
- Priorities, ...
Basic Concepts
ImplementationDesignAnalysis
Course
Contributions
Modern software development and its integration with the course.
LTO
OD
OO
AD
LabCl a
ss
Page 4
LTOOD/OOAD – Verified Software Systems 4
Exercises and Lab Classes
o Joint for OOAD and LTOOD
o Two shifts, several groups of 4 persons each
o First exercise on 30 Oct 2007
o Location: HS20, room 215
Contact persons:
Miguel Garcia [email protected]
Page 5
LTOOD/OOAD – Verified Software Systems 5
Exam
o Individual exams for LTOOD and OOAD
o At the end of the term
o In written form
o Closed-book
Page 6
Object Orientation I
Introduction
Page 7
LTOOD/OOAD – Verified Software Systems 7
What is an Object?
Light
on()
off()
brighten()
dim()
Type name
Interface Objects couple
characteristics
and relationships
with behaviour
Object creation: Light lt = new Light();
Message passing: lt.on();
Page 8
LTOOD/OOAD – Verified Software Systems 8
Alan Kay’s 5 Rules for OO
n Everything is an object.
n Each object has its own memory made up
of other objects.
n Every object has a type.
n All objects of a particular type can receive
the same messages.
n A program is a bunch of objects telling each
other what to do by sending messages.
Page 9
LTOOD/OOAD – Verified Software Systems 9
Classes
o A class defines the methods and attributes
(together called members) shared by all
objects of a certain kind.
o In other words: A class sums up the
commonalities of all objects belonging to the
class.
Class
Object 1
Object 2
Object 3
Object 4
many objects can belong to the same class
Page 10
LTOOD/OOAD – Verified Software Systems 10
Class – Instance – Object
o When you create an object:
Light lt = new Light();
you create an instance of the class called
Light and bind it to the variable lt.
o An instance is a specific occurrence of a
member of its class.
o Object is a synonym for instance.
Example: Your car is one of many
cars. It is an instance of the class Car.
Page 11
LTOOD/OOAD – Verified Software Systems 11
Example of a Simple Class
class Rectangle {
int x; int y;
int width; int height;
void draw() {
// ...
}
void erase() {
// ...
}
}
box : Rectangle
x = 100; y = 200;
width = 10;
height = 20;
A class
instance
A class
definition
Page 12
LTOOD/OOAD – Verified Software Systems 12
Objects Hide Complexity
Interface
Class Creator Class User
Page 13
LTOOD/OOAD – Verified Software Systems 13
Example of Hidden Complexity
class Person {
double height ;
double weight ;
double calculateBMI () {
return weight/(height*height);
}
}
Person p = new Person();
p.height = 1.80 ; p.weight = 75 ;
p.calculateBMI () ;
Creator of the
class ...
... needs to
know the details
about the body-
mass-index
User of the class
has a very
easy life.
Page 14
Object Orientation
Approach and Concepts
Page 15
LTOOD/OOAD – Verified Software Systems 15
The Object-oriented Approach
“The OO approach has been exploited by a wide
range of applications (user interface construction,
operating systems, databases, ...).
Why is it so successful?
1. Close Relationship between software models and
physical systems
2. Improved Resilience of the software models
3. Increased Reusability of the components of the
software models (“the 3 Re’s”).
[Abadi, Cardelli: A Theory of Objects]
Page 16
LTOOD/OOAD – Verified Software Systems 16
1. Relationship between SWM and PM
The analogy with a physical model (PM) can
be useful in the development of a software
model (SWM)
( object-oriented analysis process).
Light
on()
off()
brighten()
dim()
(see: Simula [Dahl&Nygaard] as the root of OO)
Page 17
LTOOD/OOAD – Verified Software Systems 17
2. Resilience of SWM
Resilience of design in the face of changes is a
consequence of building abstractions. Objects
form natural data abstraction boundaries and
help focus a design on system structure
instead of algorithms.
Algorithms are factored into methods that are
attached to objects, making the objects
behaviorally autonomous.
Because of object abstractions, a design can
evolve with fewer pervasive reorganizations
( object-oriented design process).
Light
on()
off()
brighten()
dim()
Page 18
LTOOD/OOAD – Verified Software Systems 18
3. Reusability of SWMs
Objects are naturally organized in taxonomies
during analysis, design, and implementation.
This hierarchical organization encourages the
reuse of methods and data that are located
higher in the hierarchy
( object-oriented implementation process).“
Shape
Circle Square Line
... ... ...
Page 19
LTOOD/OOAD – Verified Software Systems 19
Concept: Inheritance I
Inheritance …
o … automatically duplicates the
interface
o … reuses interface and
implementation but allows
extension
o … relates classes that
share a part
of their definition
(therefore each
Circle, e.g., is still
a Shape).
Line
draw()
erase()
length()
Shape
draw()
erase()
Circle
draw()
erase()
Square
draw()
erase()
Page 20
LTOOD/OOAD – Verified Software Systems 20
Inheritance II
Inheritance allows:
o redefinition of inherited methods (draw())
n same method name
n same argument type list
n same return type
o addition of new methods (length())
o addition of new data members
method
overriding
Page 21
LTOOD/OOAD – Verified Software Systems 21
Concept: Overriding
o You might need to do things differently in a
sub-class.
o Supply a new implementation of a method.
Page 22
LTOOD/OOAD – Verified Software Systems 22
Deduce Meaning from Context
o You say:
n Wash the car.
n Wash the shirt.
n Wash the dog.
o You don‘t say:
n carWash the car.
n shirtWash the shirt.
n dogWash the dog.
Page 23
LTOOD/OOAD – Verified Software Systems 23
Concept: Method Overloading
o ... computers can also figure out the context:
o This is called overloading
n substantially different from overriding!
n overloading is about “name economy”
n overriding is about “object autonomy”
o Not special to OO, present in other paradigms
as well
class SuperWasher {
void wash (Shirt s) { ... }
void wash (Car c) { ...}
void wash (Dog d) { ...}
}
Page 24
LTOOD/OOAD – Verified Software Systems 24
Goal: Safe and Flexible Substitutability
o One piece of code defined for objects of a
(super-) class also works for all objects of its
sub-classes:
o It does not matter whether s is actually a
Circle, Square or Line.
Line
Shape
Circle
Square
Shape s ;
// ...
s.draw () ;
s.erase () ;
Page 25
LTOOD/OOAD – Verified Software Systems 25
Means: Polymorphism
o An object can appear as any of all its ancestors
Ellipse
draw()
erase()
Circle
draw()
erase()
Shape
draw()
erase()
An Ellipse is a Shape.
A Circle is an Ellipse.
A Circle is also a Shape.
[ Monomorphism: An Object
is related to exactly one type
(class). ]
Page 26
LTOOD/OOAD – Verified Software Systems 26
Means: Dynamic Binding
o Which class definition to be related (i.e., which
implementation to be called) is determined at
runtime based on the class used for object
creation.
draw()
draw()
draw()
draw()
dynamic
binding
mechanism
Circle.draw()
Square.draw()
Rectangle.draw()
o This is essential for safe and flexible
substitutability.
Page 27
LTOOD/OOAD – Verified Software Systems 27
Example: Writing General Codevoid doStuff (Shape s) {
s.erase () ;
// ...
s.draw () ;
}
// ...
Circle c = new Circle () ;
Triangle t = new Triangle () ;
Line l = new Line () ;
doStuff (c) ;
doStuff (t) ;
doStuff (l) ;
Each of the objects c, t and l
appears to the doStuff
method as a Shape.
This way, you have to
write the code for doStuff
only once even though you
have many sub-classes of
Shape.
Page 28
LTOOD/OOAD – Verified Software Systems 28
Variability and Polymorphism (1)
o Substitutability requires careful
consideration of the variation of
members
o Return values of methods may be
more special in subclasses
(covariance):
n Circle createShape () may replace
n Shape createShape ()
n Usage:Shape s=createShape();//expects "Shape"
Page 29
LTOOD/OOAD – Verified Software Systems 29
Variability and Polymorphism (2)
o Parameters of methods have to be more general in subclasses (contravariance):
n rotate(Shape s) may replace
n rotate(Circle c)
n Usage:rotate (new Circle ())
o Types of variables can not be changed (invariance):
n class Shape { public Color color ; … }
n color as l-value:new Shape ().color = Color.black ;
n color as r-value:Color defaultColor = new Shape ().color ;
Page 30
LTOOD/OOAD – Verified Software Systems 30
Reuse
When you need a class, you can:
1. Get the perfect one off-the-shelf
(one extreme).
2. Write it completely from scratch
(the other extreme).
3. Reuse an existing class with composition.
4. Reuse an existing class with inheritance.
Page 31
LTOOD/OOAD – Verified Software Systems 31
Reuse by Composition
Car
start()
drive()
Engine
Wheel[4]
Door[2]
Car has engine, wheels
and doors. But these
are implemented elsewhere.
o Make new classes by
composing existing ones
o Composition by “Has-A” or
“Part-Of” relationships
o Instances of existing classes
as data members
Page 32
LTOOD/OOAD – Verified Software Systems 32
Reuse by Inheritance
o Make new classes by
extending existing ones
o Inheritance by “Is-A”
relationship
o You only add what is new
or changed in the
subclasses.
Shape
draw()
erase()
Circle
draw()
erase()
Sqare
draw()
erase()
Line
draw()
erase()
Page 33
LTOOD/OOAD – Verified Software Systems 33
Inheritance vs. Composition?
Engine
Car
Wheel[4]
Window[6]
Door[2]
Car
Wheel[4]
Window[6]
Door[2]
Engine
In general, the composition
case seems to be more
frequent than the inheritance
one.
Car is an
engine?
Wrong!
Right
You start an Engine and
you start a car, so... ?
Car has an
engine
Page 34
Object Orientation
Working with Objects
Page 35
LTOOD/OOAD – Verified Software Systems 35
Object-Oriented Programs
o OO-Programs are essentially made up of
objects
o These objects send messages to each other.
o On message receive objects execute methods.
object1
object2
object3
message
message
message
Page 36
LTOOD/OOAD – Verified Software Systems 36
References
o A reference identifies an object.
However, objects by themselfs are
anonymous.
o The reference can be bound to a
variable (assignment).
n Note that this does not mean that
the variable is the reference or is
the object!
0
0
a
Page 37
LTOOD/OOAD – Verified Software Systems 37
Reference Type Variables
o Two variables might
reference different objects...
o ... but may also reference
same object
a
b3
4
a
b
0
0
3
4
Always make sure, that you know which
instance you are talking about!
o When you say a:=b, both
reference the same instance.
o If you change the object
referenced by a, you also
change that referenced by b!
Page 38
LTOOD/OOAD – Verified Software Systems 38
o Comparison by reference (identity)
n a==b
n c!=a
o Comparison by value
n a.equals(c)
n a.equals(b)
n If you create your own class, the
behavior of equals( ) is to compare
references
Comparison
a
b3
4
3
4
c
Page 39
LTOOD/OOAD – Verified Software Systems 39
Methods
o Operations on objects
o Defined inside classes
o Composed of method signature
(return type, method name, arguments)...
o ... and method body (the implementation)
<returnType> <methodName>(<argument-list>)
{
<method-body>
}}
Page 40
LTOOD/OOAD – Verified Software Systems 40
Message Sending
o Objects communicate by sending messages
(i.e., by calling methods)
receiver
objectmethod
name
parameter(s)
sender object is
the “current”
object
…cell1.setValue(100);
…
current object:
Page 41
LTOOD/OOAD – Verified Software Systems 41
Constructor
o Piece of code that is executed to created an
instance of a class and
o is used to initialize state of the instance.
Note: Make sure that you also call a
constructor of the superclass (recursively)
to initialize inherited data members!
Page 42
LTOOD/OOAD – Verified Software Systems 42
Constructor Example
o Java does some things automatically
class Person {
String name;
Person(String paramName) {
name = paramName;
}
}
class Student extends Person {
int studentId;
Student(String paramName, int paramStudentId) {
super(paramName);
studentId = paramStudentId;
}
}
The statement super(paramName) calls the constructor
Person(String) to initialize the inherited data member name.
Constructors
implicit call to Object()
Page 43
LTOOD/OOAD – Verified Software Systems 43
References to “Current” Object
o Problem:
How can you write generic code referring to
objects without having created them?
o Solution:
General name for a formal object of the
current class (the “current” object) which is
bound at runtime to an actual object.
n Java calls this this
n Some other languages self
o In addition there is a need for naming the
super object of this, which Java calls super.
Page 44
LTOOD/OOAD – Verified Software Systems 44
References to “current” object
o this vs. super
n both references to the
“current” object
o this
n lookup of members
begins at the object’s
class
o super
n lookup begins at the
super-class of the
object’s class
o Note: no super.super!
class Square extends Shape {
doStuff () {
super.draw () ;
this.draw () ;
}
}
Shape
draw()
erase()
Square
draw()
erase()
Page 45
LTOOD/OOAD – Verified Software Systems 45
Visibility
o Protection of methods and attributes.
o Nothing new to object-orientation,
but very useful for encapsulation.
o Example: visibilities in Java:
from subclasses and classes in the same
package
protected
from the defining classprivate
from class in the same packagedefault
from anywherepublic
Methods and Attributes are visible ...Modifier
Page 46
LTOOD/OOAD – Verified Software Systems 46
Castingo Using a subclass object where
a base class object is expected
implies upcasting
o If you want to access
methods of the
extended interface you
have to downcast the
object
Useful
void f()
void g()
void f()
void g()
void u()
void v()
void w()
Upcast:
always
safe
Downcast:
may fail,
must be
checkedMoreUseful
Shape s = new Circle();
Circle c = (Circle) s; // ok: s happens to be a Circle
Rectangle r = (Rectangle) s; // runtime error
Downcast examples
Page 47
LTOOD/OOAD – Verified Software Systems 47
Runtime Type Identification
o Objects “know” their type at runtime.
o Runtime Type Identification (RTTI).
o E.g., you can at least detect type problems:if (s instanceof Rectangle) {
Rectangle r = (Rectangle)s ;
…
}
else // what to do???throw new RuntimeException (
“unexcpected type ”
+ r.getClass ().getName ()) ;
o Using the Visitor pattern can avoid casts.
Page 48
LTOOD/OOAD – Verified Software Systems 48
Type Checker
Code generator
Syntax tree node
AssignmentVariable ref
Page 49
Object Orientation
More Concepts
Page 50
LTOOD/OOAD – Verified Software Systems 50
Classes Revisited
o A class definition deals with the
specification of:
n structure (attributes)
n behaviour (methods)
n inheritance (parent relationship)
o Difference between
n being a member of a class and
n being an instance of a class
n An object is an instance of its most
specific class (called “its class”), but
n is also a member of multiple classes
(the ones its most specific class
inherits from).
Ellipse
Circle
Shape
c = new Circle()
member of
instance of
Page 51
LTOOD/OOAD – Verified Software Systems 51
Abstract Classes
o Abstract classes cannot be instantiated.
o Can contain abstract methods, i.e.,
have no method body.
o Abstract classes have to be overridden by sub-
classes which then can be instantiated.
o Abstract classes can contain anything that is
possible in normal classes.
Page 52
LTOOD/OOAD – Verified Software Systems 52
Interfaces
o Cannot contain any implementation.
o Classes implement interfaces by giving bodies
for the required methods.
o “private” visibility does not make sense.
interface List {
public void add(Object o);
public Object get(int index);
}
class ArrayList implements List {
private Object[] data ;
public void add (Object o) {
/* Implementation */
}
public Object get (int index) {
/* Implementation */
}
}
Page 53
LTOOD/OOAD – Verified Software Systems 53
Multiple Inheritance
o Class inherits from multiple parents
Person
Man Woman
Profession
Doctor Programmer
FemaleDoctor
FemaleDoctor now has all the
methods and attributes of both
Doctor and Woman (and all
their superclasses).
o Can cause problems with duplicate names
n Need some means to resolve conflicts
o Not available in Java, but, e.g., in C++
Page 54
LTOOD/OOAD – Verified Software Systems 54
Forms of Typing
o Static
n type information available at compiletime only
n static typing can be checked by the compiler
o Dynamic
n type information also available at runtime
n uses inherent types of polymorphic objects
n this cannot be checked by the compiler but
only during execution
Page 55
LTOOD/OOAD – Verified Software Systems 55
Garbage Collection
o Garbage Collection
n Automatically disposes objects that are no longer
reachable
n Avoids bugs due to missing deallocation
o Explicit destruction
n It is sometimes difficult to know when to destroy.
n Can break encapsulation, b/c you need knowledge of
the whole program to determine when to destroy
Page 56
LTOOD/OOAD – Verified Software Systems 56
Metaclass
o A class’ class
n if a class is represented by an object this object's class
is called “metaclass”
n think of how a compiler would store information about
the class you defined
o Metaclasses can be made accessible to programs
n You get all sorts of information about the original class
(attributes, methods, visibility, inheritance, ...)
o This is not a necessity for OO, some languages,
e.g., C++ don’t have it.
o Other languages also have a class’ class’ class
(e.g. Smalltalk).
Page 57
LTOOD/OOAD – Verified Software Systems 57
Metaclass Example
o For details on Java, see java.lang.Class and
package java.lang.reflect.*
o Java metaclass mechanism is called reflection.
Reflection is read-only.
void inform (Object o) {
Class oClass = o.getClass () ;
System.out.println ("Classname: " + oClass.getName ()) ;
Method [] methods = oClass.getMethods () ;
for (int i = 0; i < methods.length; i++)
System.out.println ("method: " + methods [i].getName ()) ;
}
Java Example
(Note: You can also add class members,
this is called code-injection.)
Page 58
LTOOD/OOAD – Verified Software Systems 58
Java’s Metaclass Replacements
o Java lacks “real” metaclasses.
o Instead: built-in concepts.
o Modifier static for class members:
abstract class WebPage {
static private int numberOfAccesses;
static public getNumberOfAccesses(){
return numberOfAccesses ;
}
…
}// class WebPage
o Modifiers abstract and interface for
classes.
Page 59
LTOOD/OOAD – Verified Software Systems 59
Levels of Object-Orientation
Level 1: only objects, these can serve as
“prototypes” (prototype-based languages)
Level 2: objects and classes but no retrospection
on classes (e.g. C++)
Level 3: objects, classes and meta-classes (e.g.
Java)
(Level 4: object, class, class class, meta-class
meta-class class, Smalltalk)
Page 60
LTOOD/OOAD – Verified Software Systems 60
Generics
o Parameterize classes and methods with classes
n Example: List of String, List of Person
o Allows you to implement a class that deals with
objects of another type.
o Makes the language more type-safe (also known as
parametric
polymorphism)
List
add (Object p)
Object get (int index)
List
add (Object o)
Object get (int index)
List
add (T o)
T get (int index)
language
without generics:
language
with generics:
generalizes to: then equivalent to:T Object
Page 61
LTOOD/OOAD – Verified Software Systems 61
o Without generics:List dogList = new ArrayList();
dogList.add(new Dog());
dogList.add(new Cat()); //this compiles and
runs fine
o With generics:List<Dog> dogList = new
ArrayList<Dog>();
dogList.add(new Dog());
dogList.add(new Cat()); // this is a compile-
time error
o New in Java 5.
Generics in Javaclass List<E> {
void add(E data);
E get(int index);
/* ... */
};
Page 62
LTOOD/OOAD – Verified Software Systems 62
Compile-time Generics
Page 63
LTOOD/OOAD – Verified Software Systems 63
Erasure
Page 64
LTOOD/OOAD – Verified Software Systems 64
Generics in C++
o Generics are implemented as Templates
n New classes created for every use of the generic class
n Can blow up code considerably
template<class T>
class List {
public:
void add (T data) ;
T get (int index) ;
List () { /* ... */ }
private:
// ... the data ...
};
Page 65
LTOOD/OOAD – Verified Software Systems 65
Generics with Wildcards
o Generics allow to specify that a type is not
known (wildcards)
List<?> list = new ArrayList<String> () ;
list.add (new Object ()) ; // does this work?
Object o = list.get (0) ; // what about this?
o Constrained Wildcards (bounded polymorphism)
n “Any list that is a list of something that is a member of
Shape”
n Also: ? super Shape.
void draw (List<? extends Shape> shapes) {
for (Shape s : shapes) s.draw();
}
Here you know that everything in shapes is a shape, because
shapes is a list of one of the subtypes of Shape (including Shape).
Page 66
LTOOD/OOAD – Verified Software Systems 66
Generics’ Catches
o Be careful about what the bounding means
void addCircle (List<? extends Shape> shapes) {
shapes.add (new Circle ()); //Why does this not work?
}
shapes could e.g. be a List<Rectangle>
void addCircle (List<Shape> shapes) {
shapes.add (new Circle ()) ; //now this works
}
Instead, use:
shapes is a List<Shape>. Since
Circle certainly is a Shape, this works.
Page 67
LTOOD/OOAD – Verified Software Systems 67
Covariance
o Type relation of
List<Shape> and List<Circle>?
n No !!
o But Java arrays have the property
that there types are covariant
n String[] subtype of Object[]
Page 68
LTOOD/OOAD – Verified Software Systems 68
Subtyping
Page 69
LTOOD/OOAD – Verified Software Systems 69
Generic Methods
o Consider writing a method that takes
an array of objects and a collection
and puts all objects in the array into
the collection.
o static void fromArrayToCollection(Object[] a,
Collection<?> c)
{ for (Object o : a)
{ c.add(o); // compile time error
}}
Page 70
LTOOD/OOAD – Verified Software Systems 70
Generic Methods
o Second attemptstatic <T> void fromArrayToCollection(T[] a,
Collection<T> c)
{ for (T o : a)
{ c.add(o); // correct
}}
o Collection exampleinterface Collection<E> {
public <T> boolean containsAll(Collection<T> c);
public <T extends E> boolean addAll(Collection<T> c);
// hey, type variables can have bounds too!
}
Page 71
LTOOD/OOAD – Verified Software Systems 71
On OO: Links and References
Links to OO:
o Object FAQ - http://www.ipipan.gda.pl/~marek/objects/faq/
o Don’t fear the OOP (OO & Java Tutorial) -
http://sepwww.stanford.edu/sep/josman/oop/oop1.htm
o Sun's Java 5 page - http://java.sun.com/j2se/1.5.0/
References for Chap.1:
o Abadi, Cardelli: A Theory of Objects - Springer Monographs in
Computer Science
o Alan Kay (five rules)
o Bruce Eckel: Thinking in Java (http://www.mindview.net/Books/TIJ)