Chap2 1OO-UML
Chap2 1OO-UML
Software Engineering
1
Definition of “Object” and “Class“
Let G be the the union of all past, present, and future substantial „things“ and
concepts (G is called the universal set)
For example, G contains:
Persons: Prof. Tichy, you, , … (substantial)
Air (substantial)
My life insurance contract (conceptual)
Democracy (conceptual)
European Soccer Championship (Event → conceptual)
Swimming (activity → conceptual)
Swimming (capability → conceptual)
Blue (color/property → conceptual)
Software (conceptual)
etc.
2
Object
Def. Object: An element out of the set G that is recognizable and clearly
distinguishable from others by at least one individuum.
Def. Ω: The set of all objects. (Ω ⊂ G)
3
Class and Exemplar
Def. Class: An arbitrary category over the set of all objects Ω.
Notes
„category“ is derived from „praedicare“; one states what is part of the category and what is not.
Usually, a category results in some form of sameness of the objects in the category.
A category can also be empty. A class states the basic idea or concept of objects, independent of
their existence.
4
In which domains are these terms usually used?
entity
Reality
object
mapping
exemplar
Model
class
mapping
instance
(object-oriented) code
type
5
Further hints
Use the term „class“ if the class has been defined and the term „instance“
when an element of a given class is meant.
6
Attributes
Def. Attribute: a property that is defined and present in all exemplars of a class
its value can be specified for every exemplar independently of other exemplars and
has a clearly defined value and
the value is from a defined domain that is the same for all exemplars of that class
Notation: Attributename: Domain [= value];
7
Hints for Java programmers
Wirklichkeit
Differentiate between attribute and instance variable!
Abbildung
Modell
Often there is a 1:1 mapping of attributes to instance
variables Abbildung
(objektorientierter) Code
But the reverse is not true. Often, we need to store non-attributes such as the state or
associations in instance variables. More about this later.
Attributes may have additional constraints or assertions which cannot be expressed by the
domain of the attribute but requires additional code. (In UML, one can specify this with the
Object Constraint Language OCL)
8
Object identity
Def. Object identity: The existence of an object is independent of its attribute
values. Two objects are distinguishable even when they have the same attribute
values.
Hints
Object identity is already given by our defintion of attributes.
Two (or more) objects can be equal, without being the same. How to define equality then?
≠ ≠
9
Comparing objects
Def. Equality of order n
Equality of order 0: the objects are identical (there is only one object)
Equality of order 1 : the objects are identical, or the objects are different but have pairwise
identical values for all attributes (equality of order 0 or pairwise equality of order 0 in all
attributes). Example: apples previous page.
Equality of order 2 : equality of order 1 or pairwise equality of order 1 in all attributes.
Example: 2 bags of apples of equality order 1.
Equality of order 3 : equality of order 2 or pairwise equality of order in all attributes 2*.
etc.
* Of course we need to take into considerations associations and state as well (see later)
10
What has this to do with classes in programming
languages?
11
Substitution of objects
It should be possible to use IntTriple in the same context as IntPair
(where only x and y are used). This is called substitution of a subclass object
for a superclass object.
12
State of objects
Often, the state of objects is defined as the concatenation of all attribute
values, or simply as the sequence of bits which store the attribute
values.
This definition is problematic: For example, is the value of the attribute
„operating hours“ important for the state of a traffic light?
13
State of objects
Def. State: As long as an object is in a certain state and in the same calling or
use conext, it will always react in the same way. If the state changes, the object
will react in at least one context in a different way. (external view)
14
Hints for Java programmers
Wirklichkeit
The state of an object must be saved in
instance variables (in the same way as Abbildung
Modell
attribute values) Abbildung
(objektorientierter) Code
15
Encapsulation
Def. Encapsulation: The state is visible from the outside, but is
controlled inside the object (controlled change)
Example: the state of a traffic light should not be changed arbitrarily or at
arbitrary times
Hint: if the state is implicit, the change of an attribute value may cause a
change of state.
Example: For an egg timer, if the “remaining time” changes to 0, the egg timer
must change into state “ringing”.
16
Change of state
Example encapsulation principle: You
shouldn´t fiddle with the interior of a
recorder to set it into the state „play“
“play” “pause”
Play Pause
start Standby
“stop” “play”
17
Sending a message to an object
„Sending a message“ means that a certain object (the recipient of the message)
should perform a state change, or perform an action in the current state.
18
Methods and state changes
Methods may change the state of an object.
The available methods define the permissible state changes that can be
requestes of an object (external view)
Problem: When may I send which message to an object?
Answer: This is defined with a state diagram or state chart (see later)
19
Hints for Java programmers
Wirklichkeit
The state diagram specifies a finite automaton.
Is this automaton complete? Modell
Abbildung
Choices
Return an error
Throw an exception
Generate Java.lang.Error-Instance
„garbage in – garbage out“
Ignore
crash
20
Methode signatures
Def. A Method signature consists of
Method name
Return type
Parameter list
The parameters carry the data of the message
The receiving object (o in method call o.m() ) can be viewed as the “zero’th“ Parameter of the call, or
as address of the message.
Notation:
Methodname (Parameterlist) : Returntype;
Parameterlist:
Parametername : Type [, Parametername : Type]*
21
UML Class Diagrams
What is UML?
UML: „Unified Modeling Language“
UML is the union of three object-oriented modeling formalisms:
Booch (Grady Booch)
OOSE (Ivar Jacobson)
OMT (James Rumbaugh)
23
Notation of a class in UML
ClassName
attribute1: TypeX;
Optional block for attributes
attribute2: TypeY;
attribute3: TypeZ = initialvalue;
methodA() : TypeY;
methodB(paramN: TypeX); Optional block for methods
methodC();
ClassName ClassName
No attributes
attribute1: TypeX;
methodA() : TypeY; attribute2: TypeY;
methodB(paramN: TypeX); attribute3: TypeZ;
methodC(); no methods
24
Object/Instance diagramm
Instance indicated
by underlining and Instance of
Circle name Class Circle
radius : double;
x : double = 0; «instanceOf» myC1 : Circle
y : double = 0; radius = 1,0;
draw() x = 3,14;
hide() y = 0,7;
Instance relation
scale(factor : double) (optional) marked by
dashed and open
arrow to class, with Values of
«instanceOf» label attributes
Class Circle
with 3 attributes (also optional)
and 3 methods
myC2 : Circle
Two further Anonymous Circle instance
radius = 1,0; instances of
x = 3,14; Circle
y = 0,7;
25
Associations: Defining Relations between Objects
Motivating example:
If we want to express that a person works for a certain firm, we could add an attribute “Firm“
in class “Person”.
If we also want to know which persons work at a given firm, we would need an attribute for a
list of persons in class “Firm” (List<Person>).
Problem: How do you express that these two attributes belong together? If you
change one, you may have to change the other.
Firm Person
name: string
address: string
? name: string
employees: List<Person> employer: Firm
26
Answer: Use an association
Directed association
Note: Class diagrams are multigraphs, which means that more than one
Association may exist between a pair of nodes.
27
Added Value of Associations
?
Transactionality, ACID-principle
28
When to use Associations and when to use Attributes
Example:*
a) Rectangle b) Rectangle
0..1 topleft
Point
0..1 bottomright
topleft: Point; x: float;
bottomright: Point; y: float;
29
The Connection between Associations and Relations
A binary relation is a subset of the cross product of two sets (the sets
need not be different)
Ternery, quaternary, n-ary relations are subsets of the cross products of
3, 4, n sets.
Relations can be represented as n-dimensional arrays, tupel sets, or
graphs
A „link“ is a single elment of a cross product, a tuple, or an edge in the
graph. (in n-ary relations, an edge has more than two ends, in case n>2)
30
Example of a binary relation, in three representations
Let Firms = {f1, f2, f3} und Persons = {p1, p2, p3, p4, p5}.
A possible relation of the two sets could be:
p5 f1:Firm p1:Person
p4
p2:Person
p3 Link
p3:Person
Person
p2
f2:Firm p4:Person
p1
f3:Firm p5:Person
employes f1 f2 f3
Firm
The relation in the array above can also be specified as a tuple set:
{(f1,p1), (f1,p2), (f1,p3), (f2,p4), (f2,p5), (f3,p1), (f3,p5)}, or as a graph.
A single tuple or an edge is called a link.
31
Then what is an association?
Def. An association in UML defines the properties of relations between
sets.
The sets are given as classes.
Multiplicities specify, in how many tuples an object of a given class may
appear. (for instance: 1:1 means one-to-one, 1:n one-to-many,
m:n many-to-many)
Duplicates of tuples or duplicate of links are allowed, so relations are actually
not only sets, but can be multisets or multigraphs.
The classes in associations need not be different (relation with self is
possible).
married
0..1 wife
0..1
Person
husband
32
Example of a ternary association (Hypergraph)
Team
Ternary relation
Player
Year *
Person
n=3
k1=Year
k2= Team
k3=Person
33
Associations in UML
A relation is specified by an association in UML
Multiplicity:
Name Reading direction 0 to arbitarily many
Name, reading direction and roles are only tags to help with
interpretation. They have no exactly defined semantics.
34
Association vs. Link
An association
connects classes and
0..1 employs 0..*
specifies potential Firm Person
employer employee
relations between
examplars Association
Link
35
How to read associations
36
How to read associatins
37
Cardinalities at the ends of associations
Def. Cardinality: the number of elements of a set (→ integer ≥ 0)
Def. Multiplicity: an interval of specified cardinalities
“0..1“ means “0 or 1“
“0..*“ = “*“ means “arbitrarily many, including 0“
“1“ means “always exactly 1“
“1..*“ means “arbitrarily many, but always at least 1“
“17“ means “always exactly 17“
Careful: missing cardinality means “always exactly 1“.
38
Interpreting Multiplicity
Suppose we are given an n-ary relation and an end E with multiplicity p.
We want to define what multiplicity p at end E means.
Let K be the class at end E of the association
For the other n-1 ends choose arbitrary but fixed instances of the
corresponding classes (more than n-1 possible)
Let V be the set of links which go from the n-1 chosen instances to instances
of K.
Let M be the set of instances of class K included in the above links.
Then the multiplicity p restricts the cardinality of M.
39
Example
Given the binary (n=2) association “employs“ below, Klaus:Person
with end E=“employee“ and p=0..* PearCorp:Firma Franz:Person
Then K=Person Peter:Person
Set V
For the other end, choose instance
PearCorp : Firm
Find all links from PearCorp to an instance of class Person
Let V={(PearCorp, Klaus), (PearCorp, Franz),(PearCorp, Peter)}
Then M ={Klaus, Franz, Peter}
The multiplicity p=(0..*) limits the cardinality of M
40
Where do we need this?
n-ary Associations!
Team
1
player
Year * *
Person
41
N-ary multiplicity
K = Team
Choose instances of Person and Year and look at tuples that include
these instances plus instances of Team.
Neuer:Person BM:Team
42
N-ary Associations and multiplicity
In the above ternary association we have E/K = Team, p = 1
Choose 2002:Year, MiroslavKlose:Person, MarioBasler:Person and
HarryKoch:Person
Let V be the set of ternary relations that go from instances of Year and Person to
instances of class Team.
Then M is the set of instances of Team occuring in V
p restricts the cardinality of M
This means that the Persons MiroslavKlose, MarioBasler und HarryKoch
play in exactly one team each (not necessarily the same team) in 2002.
43
Example for Restrictions
A person can participate in arbitary many events, arbitary may persons
can participate in any event, but in each event only once:
* *
Event Person
participant
{unique}
45
Navigation of Relations
Exemplars may only send messages to other exemplars if they „know“ them
(have links to them). A link makes objects known to each other. In other words,
links establish message channels.
46
How to store information about relations?
Sometimes one would like to store information about a relation.
* *
Event Person
participant
{unique}
* *
Event Person Wrong: Alarm applies to
participant
Alarm:Time all persons
{unique}
* *
Event Person Wrong: Alarm applies to
participant
{unique}
Alarm:Time all events of a person
47
Answer: Association classes put attributes in relations
* *
Event Person Note: class
participant diagrams are
{unique} multi-hyper-
graphs with
Here only a single attribute. Participation attributed nodes
One can also add methods and edges!
Alarm:Time
But:
p1: Participation This is legal under the
t:Event p:Person
above model, but does not
p2:Participation
enforce uniqueness
48
Association classes
Hint:
The existence of an instance of an association class depends on the
existence of its relation!
If the relation is deleted, then the instance of the association class with all its
data also disapears.
Also: If one end of a relation is deleted, then the whole relation is deleted, and
the instance of association class with it!
Conclusion: Don´t use association classes like normal classes!
49
Special associations
Aggregation (specialization of association): Position of 4 is
correct
Part-whole relationship (or contains, has)
0..1 has 4
Car Wheel
1 has *
Invoice Item
50
Qualified associations
Def. Qualifier: An attribute (or combination of attributes) that partition the set
of associated exemplars
Examples
1..* 0..1
Bank Account number Person
1 1
Chessboard row, column Square
Qualifier can be one or more
scalar variables, eumerations
51
Multiplicity in qualified associations
Qualified associations always code 1:n or m:n relations, (why?)
The (frequent!) Partitionsize „1“ requires a unique qualifier
Interpretation of multiplicities:
1..* 0..1
Bank account number Person
52
Multiplicity and qualification – Example 1
1..* 0..1
Bank Account number Person
54
Multiplicity and qualification – Example 2
0..* 1..*
Bank account number Person
55
Class attributes and class methods
Math
The class as set of exemplars is itself viewed as E : double
an object. This object can have its PI : double
own attributes and methods (independent of the sqrt(a:double) : double
attributes and methods of the exemplars) cos(a:double) : double
These attributes and methods are called
class attributes and class methods.
They are marked by underlining them in the class box.
(in Java, they are marked with the keyword static.)
Class attributes and class methods exist independent of the existence of exemplars
of the class.
The class attributes and methods are available at runtime in any exemplar of the
corresponding class and can be used exactly like normal attributes and methods.
57
Constructors
Circle
Constructors are marked with the x : int
stereotype «create» y : int
They can have arbitrary names. r : int
They create exemplars. «create» make(x:int,
The return type is implicitly the class and is y:int, r:int)
not indicated.
In Java, the name of a constructor must be the same as the class.
Java constructors also have no declared return types.
Java example: public Circle(int x, int y, int r) {…}
58
Enumerations
Enumerations in UML are defined by a special form Book
of class
name : String
The attributes define the possible elements of the
enumeration. summary : String
keywords : String
Enumerations are declared with the stereotype
«enumeration»
An enumeration is linked to an object with an
association. «enumeration»
Genre
Adventure
Contemporary
(In UML, stereotypes classify model elements and thus Fantasy
provide extra information) Horror
Thriller
59
Enumerations
Book
name : String
summary : String
keywords : String
classification : Genre
«enumeration»
Genre
Alternatively, an enumeration can also be Adventure
used as a type for an attribute, rather than Contemporary
in an association. Fantasy
(Then of course we have no way to Horror
provide multiplicities, etc.)
Thriller
60
A short quiz
True or false…?
61
Inheritance
Inheritance—concepts and synonyms
Superclass
Baseclass
Generalization
Recorder
play()
record()
calibrateHead()
Is-a relationship
Videorecorder DAT-Recorder
Subclass
Specialization
Cassettedeck
63
Def. Inheritance: Let O and U be classes, and ΩO und ΩU the sets
of exemplars that make up these classes. Then U is a subclass or
specialization of O (and O superclass or generalization of U) iff
Ω U ⊆ ΩO
We also say that U „inherits“ from O.
Since exemplars of U are also a exemplars of O, we call the
relationship between O and U the is-a relation.
If O has several subclasses, then they should be disjoint (have
no common exemplars)
Example of an exception: Platypus is a mammal, but it also
lays eggs (i.e., it is also a bird)
U1 U2
64
Is the subset relation really correct?
65
Is-a relation
Suppose need to model a line. We could use the class Point for this.
Is inheritance here a good idea?
Point
x: float;
A line is not a special case of a point.
y: float; (it is acutally infinitly many points)
This model is lazy.
66
Finding superclasses
Check whether different classes have common attributes, states, associations,
or methods.
These can then be „pulled up“ into a common super class.
Inheritance offers advantages when doing so:
Avoids redundancy (shared attributes and methods need to be repeated; instead, they
are „inherited“ from the subclasses.)
There is a well-founded typing theory for inheritance
67
Liskov substitution principle
In a program with U being a subclass of O, every
exemplar of O can be replaced with an exemplar
of subclass U and the program will continue to
work correctly.
o.m();
u.m();
o = u; --Substitution
o.m(); !
69
Implications of the substitution principle (I):
Adding and deleting properties
70
Implications of the substitution principle(II)
Transitivity
71
Differentiate!
Def. Signature inheritance: A method defined (and perhaps
implemented) in a superclass transfers only the signature of the method
to subclasses.
Def. Implementation inheritance: A method defined and implemented in
a superclass transfers both the method´s signature and its
implementation to subclasses.
Implementation inheritance is not possible without signature inheritance.
Example: Java and C# provide both signature and implementation
inheritance. (how?)
72
Implications of the substitution principle(III):
Adaptation of methods
Has nothing to do
with inheritance!
73
Overriding – Example
GeometricFigure * shows *
Display
General: draws every position: Point
GeometricFigure
draw()
delete()
override
Specialized:
draws only circles
Insight:
Each of the three specializations must implement its own draw()
method
Is it even possible to implement a general draw() in
GeometricFigure?
74
Solution: Abstract methods
cursive indicates
abstract class
GeometricFigure * shows *
Display
Position: Point
draw() Def. Abstract method:
delete()
cursive indicates
abstract method
signature without
→ no implementation! implementation
If there is at least one abstract method in a class, then the class itself is abstract.
There are no exemplars of abstract classes. Why not?
The first concrete (non-abstract) class in an inheritance hierarchy “inherits” the obligation to
provide implementations for the abstract methods of abstract superclasses. Why?
75
Abstract methods, alternative notation
GeometricFigure
* shows *
{abstract} Display
Position: Point
draw() {abstract}
Alternative notation delete()
(preferred in exams ☺)
76
Interfaces
Def. interface: a named set of abstract methods, which need to be
implemented by classes that offer that interface.
Interfaces cannot be directly instantiated
A class may implement several interfaces (multiple inheritance of interfaces).
EMail «interface»
Indicates interface
«use» SMTPServer
to: String
message: String open(host: String, port: int)
send() sendMsg(to: String, msg: String)
close()
77
Use of interfaces
Interfaces transfer the obligation to implement their methods.
Interfaces provide the guarantee that certain methods are present.
Exemplars of a class that implements a certain interface can be used as if
they were an exemplar of the interface (is-a semantics).
General idea: an interface indicates how to use an object, but not what it
is.
78
Interface – example
You receive a remote control.
Although you do not know what the device is, you can use it, because you know
the interface.
79
Inheritance and interfaces
Interfaces cannot inherit!
If an interface A is extended by an interface B, then the set of abstract methods of A is a
subset of the abstract methods of B. (short: A⊆B).
When a class C implements an interface A, then the set of abstract methods of A is a subset
of the methods of C, where C may provide additional implementations.
Classes can implement several interfaces. Since this is simply a union operation
of sets, multiple inheritance of interfaces is not problematic.
if two inherited interfaces provide the same method, then we simply take the union of
the elements in the interfaces, meaning that for two inherited methods only one
remains.
Exercise: Which problems can occur with multiple inheritance of classes?
80
Implications of the substitution principle (IV):
Signature changes
Short answer: it is possible to make the types of the parameters and the
return type more or less general.
81
Implications of the substitution principle (IV):
Parameter variance
82
Example of co/contravariance
R P
A n(t:B) m(s:A)
B S Q
n(t:A) m(s:B)
contravariance covariance
of parameter t. of parameter s.
(classes and (classes and
parameters parameters
specialize in specialize in
opposite the same
83
directions.) direction.)
Contravariance and substitution principle –
Example
European
Croat
84
Contravariance and substitution principle –
Example
European e;
Croat k;
Currency cur;
Euro eu;
e.accept(eu); e.accept(cur); ??
e = k; // substitution!
e.accept(eu); ?? e.accept(cur); ??
85
Covariance und substitution principle – Example
BadenNative
Swabian
Spätzle
eat(s: Spätzle) topping: Cheese
...
s.topping.spread()
...
86
Covariance und substitution principle – Example
BadenNative b;
Swabian s;
Noodle n;
Spätzle sp;
b.eat(n); b.eat(sp);
b = s; // substitution !
b.eat(n); ?? b.eat(sp); ??
87
Covariance und substitution principle
Example with return type
BadenNative
Swabian
Spätzle
cook(): Spätzle topping: Cheese
...
s.topping.spread()
...
88
Covariance und substitution principle
Example with return type
BadenNative b;
Swabian s;
Noodle n;
Spätzle sp;
n = b.cook(); sp = b.cook(); ??
b = s; // substitution !
n = b.cook(); ??
89
Co/contravariance again
A R
Implementation
x: int n(t:B) uses attributes x
What happens and y
with
covariance?
B S
y: float n(t:A) Implementation
may use only x
contravariance
of parameter t
R r; S s;
r.n(new A); r.n(new B);
r = s; // Substitution !!!
r.n(new A); r.n(new B);
90
Co/contravariance again
Exercise 1: Examine the example before for contravariance of the
parameters. Which ones of the calls work/don´t work? Why?
Exercise 2: Examine again the example before, this time for return
values. Let class R have a method m():A and S a Method m():B.
Which ones of the expressions r.m().x und r.m().y are legal
before and after the substituion of r=s, given covariance? What
happens for contravariance? What is caught by the compiler, and what
at runtime?
91
Quick quiz…
What is allowed for input parameters?
variance (general)
covariance
contravariance
invariance
92
Implications of the substitution principle(IV):
Permitted variance
To allow the substitution principle, the following modifications of
parameter and return types are permitted in the overriding methods
93
Hint for Java-Programmers
Wirklichkeit
“
Abbildung
double Modell
Java primitive types
Abbildung
have the following (objektorientierter) Code
long
int char
„ short byte
see: The Java Language Specification 2.0, §5.1.2, Widening Primitive Conversion
94
Implications of the substituion principle: general
A subclass has the same or weaker preconditions as the superclass.
For methods this means that when substituting a subclass for a superclass,
the preconditions of the subclass methods are satisfied.
95
Implications of the substitution principle(V)
Rectangle
Example:
Square
96
Implications of the substitution principle(V)
class Rectangle {
private double breadth, height;
97
Implications of the substitution principle(V)
class Square extends Rectangle {
public setBreadth(double b) {
super.setHeight(b);
super.setBreadth(b);
}
public setHeight(double h) {
super.setHeight(h);
super.setBreadth(h);
}
}
98
Implications of the substitution principle(V)
// somewhere else....
public void compute (Rectangle r) {
r.setHeight(5);
r.setBreadth(6);
assert(r.getHeight()*r.getBreadth()==30);
}
// somewhere else...
Rectangle r = new Square(....); //substitution
compute(r); // assert fails. Why?
99
Implications of the substitution principle(V)
Postcondition of Rectangle.setBreadth(..):
In others words, the subclass methods expect more and deliver less.
Which means the substitution principle is not satisfied.
100
Implications of the substitution principle(V)
Logically, the model is correct, because squares are indeed a subset of
rectangles.
But the behavior of the classes is not consistent.
We have to check whether pre- and postconditions „fit“ before we
substitute one class for another.
Only if superclass objects can be substituted correctly by subclass
objects is it true that a subclass object can be used in the context of a
superclass object.
101
Has nothing to
Polymorphism do with object
orientation or
inheritance!
Polymorphism means „having many forms“.
“Static polymorphism“ (Overloading)
There can be several methods with the same name (but their signatures*
must be different, so the compiler can determine which one to choose)
“Dynamic polymorphism“ (using inheritance)
At runtime, the method with a given signature is chosen that is the most
specialized one in the inheritance hierarchy, starting with the class of the
current object.
* In Java, the parameter list must be different, in Haskell the return type
102
Example:
dynamic polymorphism
Dog
howl()
Dog d; Canis
d = w;
Canis lupus
d.howl();
Polarwolf
howl()
Canis lupus arctos
103
Example:
Dynamic polymorphism
Dog
howl()
Dog d; Canis
d = w;
Canis lupus
d.howl();
Polarwolf
howl()
Canis lupus arctos
104
Example:
Dynamic polymorphism
Dog
howl()
Dog d; Canis
d = w;
Canis lupus
substitution allowed
d.howl(); (is-a Semantics)
Polarwolf
howl()
Canis lupus arctos
105
Example:
Dynamic polymorphism
Dog
howl()
Dog d; Canis
d = w;
Canis lupus
d.howl();
Polarwolf
howl()
Canis lupus arctos
106
What else is there in class diagrams?
aClass Note
comment, note
operation(p: paramTyp) or code
107
Visibility/access rights
Attributes and methods of an object may be protected from access by other
classes. Access is allowed for:
private (“-“): only (but all!) Exemplars of the same class
protected (“#“): Exemplars of the same class and all derived classes
In Java, “protected”
package (“~“): Exemplars of the same package (subsystem/library) includes package
public (“+“): every Exemplar visibility
The visibility symbol (-, #, ~, +) is simply placed before the name of the attribute or method
Note: “private“ does not mean “only this exemplar“!
The protection is limited to compile time only.
All access rights can be changed at runtime (e.g. with BCEL forJava). They do not protect from malicious attacks.
They are only meant for a clean model that avoids excessive information distribution and makes the software easier
to modify.
108
Visibility: Example
Circle
-radius : double;
#x: double = 0;
#y : double = 0;
+setRadius(r: double)
+setCenter(p:Point)
+draw()
+hide()
+scale(factor : double)
109
Literature
Bruegge, A.H. Dutoit, Object-Oriented Software Engineering: Using
UML, Patterns and Java,
Read Chap. 2! (not as detailed as this lecture.)
110
Exercises
1. What are class attributes and class methods called in Java? Is there a difference to UML?
2. How do associations and inheritance differ? (Hint: Which UML elements are primarily
addressed in associations, and which ones in inheritance?)
3. What may occur in Java interfaces? Is there a difference to UML interfaces?
4. Suppose we had interfaces, but no abstract methods in classes. Would this cause a problem
or disadvantage?
5. What type of parameter variance is permitted in Java? (Don´t forget return types.)
111