Professional Documents
Culture Documents
Object Oriented
Programming Techniques
UML representation
2D Shape
Polygon
Circle
...
Triangle
Rectangle
FilledCircle
- colour : int
+ draw() : void
class Circle {
protected Point center;
protected double rad;
public double getArea() { ...}
public void draw() { ...}
}
Inheritance
Java example
Class system
Factor
structure
behavior
Objects
Inheritance
Java example
Point
Shape2D
- x : int
- y : int
# org : Point
+getX() : int
1
+getY() : int
+whoAreYou(): String
+draw() : void
+whoAreYou() : String
+perimeter() : double
+area(): double
+draw() : void
1
Rectangle
Circle
- pc2 : Point
- radius : int
+perimeter() : double
+area(): double
+draw() : void
+perimeter() : double
+area(): double
+draw() : void
Inheritance
Java example
Hierarchy
of classes
Superclasses and subclasses
public class Shape2D { }
public class Circle extends Shape2D { }
public class Rectangle extends Shape2D { }
A
Inheritance
Java example
public class Shape2D {
protected Point org;
public Shape2D(Point org) {
this.org = org;
}
public String whoAreYou() {return "SHAPE2D"; }
public void draw() {
System.out.println ("I am a generalized
Shape2D. Don't know how to execute draw");
}
public double perimeter() { return 0.0; }
public double area() { return 0.0; }
}
Inheritance
Java example
public class Circle extends Shape2D {
protected double radius;
public Circle(Point pc, double radius) {
super(pc);
this.radius = radius; }
// Specific Interface
public String whoAreYou()
{ return "CIRCLE"; }
public void draw()
{System.out.println(toString());}
public double perimeter()
{ return 2.0 * Math.PI * radius;}
public double area()
{return Math.PI * radius * radius;}
// String conversion
public String toString() {
return "CIRCLE with Center " +
org.toString() + " and radius " + radius;
}
}
Ioan Salomie - OO Programming Techniques
Inheritance
Java example
public class FilledCircle extends Circle {
private int color;
public FilledCircle(Point pc, double radius, int
color) {
super(pc, radius);
this.color = color;
}
public String whoAreYou() {
return "FILLED-CIRCLE";
}
public void draw() {
System.out.println(toString());
}
public String toString() {
return "FILLED-CIRCLE Center in: " +
org.toString() + " and radius: " + radius +
"color:" + color;
}
}
Ioan Salomie - OO Programming Techniques
10
11
Constructors in the
context of inheritance
Shape2D
Order of instance
variable initialization
Circle
Rectangle
FilledCircle
FilledRectangle
Superconstructors
Calling Order
12
Inheritance specific
Constructors in class hierarchies
Call to
super(pc, radius);
the first statement in the subclass' constructor
public FilledCircle (Point pc, double radius,
int color) {
super(pc, radius);
this.color = color;
}
Same
13
14
this()
default constructor of
ColoredPoint()
default super constructor is invoked;
Ioan Salomie - OO Programming Techniques
15
Special rules
No constructor
in the subclass
Compile error
A parameter
superclass
Default constructor is not implicitly provided
16
Other remarks
Inheritance -
strong coupling
between constructors
any modification in the superclass
constructor is reflected in the subclass
constructor
Limit the
number of hierarchy
levels to 3 or 4
For code reuse, prefer delegation
over inheritance
17
18
Binding
Binding
(name, code)
Static
binding
binding
19
class
Object
The class of an object - when is
determined ?
A variable of reference type - holds a
reference to an object
The variable may hold references to
objects of different classes subject to
the substitutability of subtypes
20
Shape2D
Circle
Rectangle
21
of its
superclass
Adds new features
Specialization and generalization
Every
22
Shape2D
Circle
Rectangle
23
24
Substitutability of
subtypes
A
25
Conversion of
reference types
Governed by
subtype relation
Widening
(downcasting)
26
Conversion of
reference types
Differences
between conversions of
primitive types and reference types
In case of primitive types
Change of representation
27
Polymorphism
Polymorphism
a method
Polymorphism [Cardelli & Wegner]:
Universal
Parametric
Inclusion
Ad-hoc
Coercion
Overloading
28
flexibility
Type checking => rigidity
Compatible by linking
Trade - off
29
Polymorphism
Type checking and linking
Static
linking
linking
30
Polymorphic assignments
In
In
OO languages
Polymorphic assignment
Powerful form of assignment
Rule of assignment
31
Rule of Assignment
Example
class Shape2D { }
class Circle extends Shape2D { }
class Rectangle extends Shape2D { }
Shape2D s1, s2;
// polymorphic assignments
// no explicit casting is necessary
s1 = new Circle();
s2 = new Rectangle();
Circle c1;
// following line: compile error even though actually
// s1 holds a reference to a Circle instance
// the declared type of s1 is Shape2D and this is not subtype
// of left hand side (i.e. Circle)
// type checking takes place at compile time
c1 = s1;
32
Rule of Assignment
Downcasting
Casting a reference variable to a
subtype of its declared type
Explicit casting (in Java) is allowed at
compile time
The validity of explicit casting checked at run time
In case of invalid cast
ClassCastException
Example
c1 = (Circle) s2;
compile time
run time
33
Downcasting techniques
Pessimistic approach
34
Downcasting techniques
Optimistic approach
try {
//
Circle cref = (Circle) s2;
//
} catch (ClassCastException e) {
// do something
}
35
Downcasting techniques
Rectangle
class
defines getNoCorners()
not defined in the Shape2D
Shape2D s1 = new Rectangle();
//
// compile error
// validity of method invocation is
// statically checked
int nc = s1.getNoCorners();
//
Ioan Salomie - OO Programming Techniques
36
Downcasting techniques
Shape2D s1 = new Rectangle();
//
if(s1 instanceof Rectangle) {
Rectangle r1 = (Rectangle) s1;
int nc = r1.getNoCorners();
//
}
Main question
37
int[]
A[]
B[]
38
OK
Shape2D sa[];
Circle ca[] = new Circle[10];
//
sa = ca; // polymorphic assignment
Shape2D s1 = sa[2];
Circle c1 = ca[3];
Compile
error
Circle c2 = sa[0];
Explicit downcasting is necessary
Circle c2 = (Circle)sa[0]; // ok
39
40
Overriding
Overriding
Class, subclass
Method specialization
Subclass method has the same elements
with the method in the superclass
Name
Signature
Return type
Overloading
41
Overriding
class A {
public void m() { }
}
class B extends A {
public void m() { }
}
Method m of class A is overridden by
implementation of method m in class B
For a given object, only one m is available to be
invoked
A a = new A();
B b = new B();
a.m(); // call m of class A
b.m(); // call m of class B
42
Overriding
Invoking methods
public class Point { }
public class ColoredPoint extends Point { }
public class Point {
public boolean equals (Object other) {
if(other != null) && other instanceof Point) {
Point p = (Point) other;
return (x == p.x) && (y == p.y);
}
else {
return false;
}
}
//
}
43
Overriding
Invoking methods
public class ColoredPoint extends {
public boolean equals (Object other) {
if(other != null) && other instanceof
ColoredPoint) {
ColoredPoint p = (ColoredPoint) other;
return (super.equals(p) &&
color.equals(p.color));
}
else {
return false;
}
}
//
}
44
Rectangle
Circle
# pc2 : Point
# radius : int
+ whoAreYou(): String
+perimeter() : double
+area(): double
+draw() : void
+ whoAreYou(): String
+perimeter() : double
+area(): double
+draw() : void
FilledRectangle
FilledCircle
- color : int
- color: int
+ whoAreYou(): String
+draw() : void
+ whoAreYou(): String
+draw() : void
45
46
Shape2D s;
if(cond) s = new Circle();
else s = new Rectangle();
s.draw();
The
47
polymorphic method
invocation:
var.m();
crtClass = the class of the object referenced by var
repeat
if m() is implemented by crtClass
then
invoke m()
break
else crtClass = the superclass of crtClass
until (crtClass != Object)
48
Polymorphism and
collections
Heterogeneous collections
Definition
Some methods of the superclass are
overridden in the subclasses
Polymorphic behaviour when
processing heterogeneous collections
ex. When iterating collections
Calling the most appropriate method
49
Heterogeneous collections
*
Shape2D
Circle
Image
Rectangle
No multilevel images
*
Shape2D
Circle
Rectangle
Image
50
Heterogeneous collections
*
Employee
Manager
Personnel
Worker
*
Employee
Manager
Worker
Personnel
51
Heterogeneous
collection processing
Point
Shape2D
- x : int
- y : int
# org : Point
+getX() : int
1
+getY() : int
+whoAreYou(): string
+draw()
Rectangle
Circle
- pc2 : Point
- radius : int
+ whoAreYou():string
+perimeter() : double
+area(): double
+draw() : void
+whoAreYou():string
+perimeter() : double
+area(): double
+draw() : void
Image
- img: set of Shape2D
- ns : int
+ add(Shape2D) : bool
+ whoAreYou():string
+perimeter() : double
+area(): double
+draw() : void
52
Heterogeneous collection
processing
public class Image extends Shape2D {
private Shape2D[] img = new Shape2D[MAXSIZE];
private int ns; // effective number of shapes
//
public void draw() {
for(int i = 0; i < ns; i++) {
img[i].draw(); // polymorphism - dynamic linking
}
}
public double area() {
double a = 0.0;
for (int i =0; i<ns; i++) {
a += img[i].area(); // polymorphism - dynamic linking
}
}
}
img
...
53
54
55
Abstract classes
Discussion in
56
Abstract class
UML representation
Shape2D
{ abstract }
+ area() : double
+ draw() : void
Rectangle
+ area() : double
+ draw() : void
Circle
+ area() : double
+ draw() : void
57
Abstract classes
public abstract class Shape2D {
protected Point org;
public Shape2D(Point org) {
this.org = org;
}
/* ------- Specific Interface Methods --------- */
abstract public String whoAreYou();
abstract public void draw();
abstract public double perimeter();
abstract public double area();
}
58
Abstract classes
A
59
Abstract classes
How should we
approach the
abstract methods?
the subclass defines the abstract
method
the subclass redefines it as abstract an
let its subclasses to approach it
60
Abstract classes
It
It
public class C {
61
62
Selective inheritance
Adapter classes
Abstract
methods
context
Alternative to abstract classes
The methods that are implemented with a
default behavior (common: empty
implementation body)
Solution to selective inheritance
63
Selective inheritance
Adapter classes
public class Adapter {
public int m1() { }
public double m2() { }
public String m3() { }
// other class resources
}
// Alpha overrides m1 and m3
public class Alpha extends Adapter {
public int m1() {
// m1 specific implementation
}
public String m3() {
// m3 specific implementation
}
// other class resources
}
// Beta overrides m1 and m2
public class Beta extends Adapter {
public int m1() {
// m1 specific implementation
}
double m2() {
// m2 specific implementation
}
// other class resources
}
Ioan Salomie - OO Programming Techniques
64