You are on page 1of 32

Technical University of Cluj-Napoca

Computer Science Department

Object Oriented
Programming Techniques

Classes and Inheritance

Professor Ioan Salomie


Spring 2010

Ioan Salomie - OO Programming Techniques

Classes and Inheritance


Part 1
Inheritance

Ioan Salomie - OO Programming Techniques

UML representation
2D Shape

Polygon

Circle
...

Triangle

Rectangle

Ioan Salomie - OO Programming Techniques

UML to Java mappings


Circle
# center : Point
# rad : double
+ getArea() : double
+ draw() : void

FilledCircle
- colour : int
+ draw() : void

class Circle {
protected Point center;
protected double rad;
public double getArea() { ...}
public void draw() { ...}
}

class FilledCircle extends Circle {


private int colour;:
public void draw() { ...}
}

Ioan Salomie - OO Programming Techniques

Inheritance
Java example
Class system
Factor

(Point, Circle, Rectangle)


out the commonalities

structure
behavior
Objects

of classes Circle and Rectangle


will be abstracted in the class Shape2D
Shape2D superclass for Circle and
Rectangle
Attribute Point of Shape2D:
inherited by Circle (as centre)
inherited by Rectangle (as one corner)

Ioan Salomie - OO Programming Techniques

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

Ioan Salomie - OO Programming Techniques

Inheritance
Java example
Hierarchy

of classes
Superclasses and subclasses
public class Shape2D { }
public class Circle extends Shape2D { }
public class Rectangle extends Shape2D { }
A

class hierarchy can be extended with


other classes

public class FilledCircle extends Circle { ... }


public class FilledRectangle extends Rectangle { ...}

Ioan Salomie - OO Programming Techniques

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; }
}

Ioan Salomie - OO Programming Techniques

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

Constructors in the context


of inheritance
Initialization steps

Initialization of the inherited variables


Initialization of the self defined
variables
Invoking

one of the superclass


constructors

Ioan Salomie - OO Programming Techniques

11

Constructors in the
context of inheritance

Shape2D

Order of instance
variable initialization

Circle

Rectangle

FilledCircle

FilledRectangle
Superconstructors
Calling Order

Ioan Salomie - OO Programming Techniques

12

Inheritance specific
Constructors in class hierarchies
Call to

the superclass constructor:

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

policy for the class Circle:

public Circle(Point pc, double radius) {


super(pc);
this.radius = radius;
}

Ioan Salomie - OO Programming Techniques

13

this() and super()


import java.awt.Color;

public class ColoredPoint extends Point {


private Color color;
public ColoredPoint(double x,double y,Color color) {
super(x,y);
this.color = color;
}
public ColoredPoint(double x, double y) {
this(x, y, Color.black); // default color value
}
public ColoredPoint() {
color = Color.black;
}
}

Ioan Salomie - OO Programming Techniques

14

super() and this()


super()

superclass constructor invocation


super() invocation - first statement in the
subclass constructor
In ColoredPoint class
super(x,y) invokes super(double, double) in the
superclass;

this()

invokes a constructor of this class that


matches the given signature
should be the first statement in the
constructor
this(x, y, Color.black) invokes the
constructor ColoredPoint(double, double,
Color)
In the

default constructor of
ColoredPoint()
default super constructor is invoked;
Ioan Salomie - OO Programming Techniques

15

Special rules
No constructor

in the subclass

Default constructor is provided by default


It invokes the default constructor of the
superclass
public class SubC extends SupC {
public SubC() { super(); }
// fields and methods
}
No default

constructor in the superclass

Compile error
A parameter

constructor is defined in the

superclass
Default constructor is not implicitly provided

Ioan Salomie - OO Programming Techniques

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

Ioan Salomie - OO Programming Techniques

17

Classes and Inheritance


Part 2
Subtypes and
Polymorphism

Ioan Salomie - OO Programming Techniques

18

Binding
Binding

(name, code)
Static

binding

Compile time binding


Dynamic

binding

Run time binding

Ioan Salomie - OO Programming Techniques

19

Variable and Types,


Objects and Classes
Variable

Storage location, associated type


Variable type - when is determined
Object and

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

Ioan Salomie - OO Programming Techniques

20

Inheritance and subtypes

Shape2D

Circle

Rectangle

Ioan Salomie - OO Programming Techniques

21

Inheritance and subtypes


Subclass extends features

of its

superclass
Adds new features
Specialization and generalization
Every

instance of the subclass is an


instance of the superclass and not
vice versa
Every circle is a Shape2D but not
every Shape2D is a Circle

Ioan Salomie - OO Programming Techniques

22

Inheritance and subtypes

Inheritance, types and subtypes


Each class defines a type
All instances of a class - the set of valid type values
Every instance of a subclass is also an instance of its
superclass
The type defined by subclass is valid subset of the type
defined by its superclass
The set of all instances of a subclass is included in the set of
all instances of its superclass
Subtype relation determined by the subset relationship
between the value set of types
For example: int is a subtype of long since the set of all int
values is a subset of the set of all long values

Shape2D
Circle

Rectangle

Ioan Salomie - OO Programming Techniques

23

Inheritance and subtypes


Subtype relation

applies to class types,


interface types and primitive types
Each class defines a type
Class inheritance relation - is a subtype
relation

Each interface also defines a type


Interface extension and implementation
relations are also subtype relations

Ioan Salomie - OO Programming Techniques

24

Substitutability of
subtypes
A

value of a subtype can appear


wherever a super-type is expected
In the context of classes and objects
A subclass object can appear wherever
a superclass object is expected
An instance of a subclass can always
substitute for an instance of its superclass

Ioan Salomie - OO Programming Techniques

25

Conversion of
reference types
Governed by

subtype relation

Widening

The conversion of a subtype to one of


its supertypes
Widening is always allowed
Is carried out implicitly whenever
necessary
Narrowing

(downcasting)

The conversion of a supertype to one of


its subtypes
Requires explicit casts
Allowed at compile time
Not always safe may generate run
time exceptions
Ioan Salomie - OO Programming Techniques

26

Conversion of
reference types
Differences

between conversions of
primitive types and reference types
In case of primitive types
Change of representation

In case of reference types


No effect on representation

Ioan Salomie - OO Programming Techniques

27

Polymorphism
Polymorphism

taking many forms


Polymorphic behavior of

a method
Polymorphism [Cardelli & Wegner]:
Universal
Parametric
Inclusion

Ad-hoc
Coercion
Overloading

Ioan Salomie - OO Programming Techniques

28

Polymorphism and type


checking
Polymorphism =>

flexibility
Type checking => rigidity
Compatible by linking
Trade - off

Ioan Salomie - OO Programming Techniques

29

Polymorphism
Type checking and linking
Static

linking

Static type checking


Guarantees the correctness
Rigid interpretation

Dynamic type checking


Invalid combination
Dynamic

linking

Static type checking


Guarantees the correctness
Flexible interpretation

Dynamic type checking


doesnt guarantees the correctness
Flexible interpretation

Ioan Salomie - OO Programming Techniques

30

Polymorphic assignments
In

static programming languages


such as C
Left hand side and right hand side of an
assignment must be of compatible types

In

OO languages

Polymorphic assignment
Powerful form of assignment
Rule of assignment

Ioan Salomie - OO Programming Techniques

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;

// Explicit cast is necessary here


c1 = (Circle) s1; // ok, explicit cast

Ioan Salomie - OO Programming Techniques

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

Ioan Salomie - OO Programming Techniques

33

Downcasting techniques
Pessimistic approach

if(s2 instanceof Circle) {


Circle cref = (Circle) s2;
}
else {
// do something else
}

Ioan Salomie - OO Programming Techniques

34

Downcasting techniques
Optimistic approach

try {
//
Circle cref = (Circle) s2;
//
} catch (ClassCastException e) {
// do something
}

Ioan Salomie - OO Programming Techniques

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

Why not declare s1 as Rectangle ??


Answers

Ioan Salomie - OO Programming Techniques

37

Subtypes and arrays


Rule 1

All array types (i.e. int[], double[]) are


subtypes of Object
Rule 2

If class or interface B is subtype of class or


interface A then B[] is also subtype of A[]
Object

int[]

A[]

B[]

Ioan Salomie - OO Programming Techniques

38

Subtypes and arrays


The following sequence is

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

Ioan Salomie - OO Programming Techniques

39

Classes and Inheritance


Part 3
Overriding methods and
Polymorphic method calls

Ioan Salomie - OO Programming Techniques

40

Overriding
Overriding

Class, subclass
Method specialization
Subclass method has the same elements
with the method in the superclass
Name
Signature
Return type
Overloading

Methods of the same class


Same name
Different signatures

Ioan Salomie - OO Programming Techniques

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

Overriding and final methods


Ioan Salomie - OO Programming Techniques

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;
}
}
//
}

Ioan Salomie - OO Programming Techniques

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;
}
}
//
}

equals of ColoredPoint overrides equals of Point


equals method of Point is invoked through
reference super
Ioan Salomie - OO Programming Techniques

44

Inheritance and overriding


Shape2D
# org : Point
+whoAreYou() : String
+perimeter() : double
+area(): double
+draw() : void

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

Ioan Salomie - OO Programming Techniques

45

Inheritance and overriding

FilledCircle cp1 = new


FilledCircle();
FilledRectangle dp1 = new
FilledRectangle();
System.out.println(cp1.area());
System.out.println(cp1.perimeter());
System.out.println(dp1.area());
System.out.println(dp1.perimeter());

Ioan Salomie - OO Programming Techniques

46

Polymorphic method call


Class system

(Point, Circle, Rectangle)

Shape2D s;
if(cond) s = new Circle();
else s = new Rectangle();
s.draw();
The

invoked draw() method depends on


the actual class of the object referenced
by s at runtime
It doesnt depends on the declared type of s
This is polymorphic method invocation
Implementation of a method is bound to an
invocation dynamically at run time
Ioan Salomie - OO Programming Techniques

47

Dynamic binding algorithm


Consider the

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)

Ioan Salomie - OO Programming Techniques

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

Ioan Salomie - OO Programming Techniques

49

Heterogeneous collections
*
Shape2D

Circle

Image

Rectangle
No multilevel images
*
Shape2D

Circle

Rectangle

Image

Allows for multilevel images

Ioan Salomie - OO Programming Techniques

50

Heterogeneous collections
*
Employee

Manager

Personnel

Worker

*
Employee

Manager

Worker

Personnel

Multilevel Personnel not appropriate

Ioan Salomie - OO Programming Techniques

51

Heterogeneous
collection processing
Point

Shape2D

- x : int
- y : int

# org : Point

+getX() : int
1
+getY() : int
+whoAreYou(): string
+draw()

+(v) whoAreYou() : string


+(v) perimeter() : double
+(v) area(): double
+(v) draw() : void

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

Ioan Salomie - OO Programming Techniques

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

...

Ioan Salomie - OO Programming Techniques

53

Generic methods through dynamic


linking and polymorphism

Example - external method to compare the area


of two generic Shape2D objects
Alternative to compareTo method defined by the
Comparable interface
public Class Shape2D implements Comparable { }

public int compArea(Shape2D s1, Shape2D s2) {


double dif = s1.area() - s2.area();
if(dif == 0) return 0;
else if (diff < 0) return -1;
else return 1;
}
// usage
Circle c1 = new Circle();
Rectangle r1 = new Rectangle();
if(compArea (c1, r1) == 0) {
// ... do equal areas
}
Ioan Salomie - OO Programming Techniques

54

Classes and Inheritance


Part 4
Abstract classes

Ioan Salomie - OO Programming Techniques

55

Abstract classes
Discussion in

the context of (Shape2D,


Circle, Rectangle) system of classes
Example analysis
Instances of Shape2D not very useful
Shape2D objects have no meaning in the
problem domain
They "keep the place" for something
class Shape2D is better to be declared as an
abstract class
Main rule
Shape2D -

modified as an abstract class

Methods are defined as abstract


Circle

and Rectangle should not be


modified

Ioan Salomie - OO Programming Techniques

56

Abstract class
UML representation

Shape2D
{ abstract }
+ area() : double
+ draw() : void

Rectangle
+ area() : double
+ draw() : void

public abstract class Shape2D {


public abstract double area();
public abstract void draw();
}

Circle
+ area() : double
+ draw() : void

public class Circle extends Shape2D {


public double area() { ...}
public void draw() { ...}
};

Ioan Salomie - OO Programming Techniques

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();
}

Ioan Salomie - OO Programming Techniques

58

Abstract classes
A

Java abstract class has at least one


abstract method
An abstract method has no definition body
Abstract methods must be defined in the
subclasses
Abstract classes could not be instantiated
into objects
References to abstract classes could be
passed as parameters in methods
Abstract class content
instance and class (static) variables,
abstract and implemented methods
constructors
Usefulness

- in the generalization process

Ioan Salomie - OO Programming Techniques

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

Ioan Salomie - OO Programming Techniques

60

Abstract classes
It

is an error to instantiate objects of class


Shape2D:
Shape2D f1 = new Shape2D (); // ERROR

It

is OK to define a method of a class


taking a parameter of type Shape2D:

public class C {

public void aMethod(, Shape2D f, ) { }


}
When calling aMethod,
instead of 'f' we have to supply a reference to an
object instance of Shape2D subclass (i.e. Circle or
Rectangle)

aMethod features a polymorphic behaviour

Ioan Salomie - OO Programming Techniques

61

Abstract classes and


polymorphism
public class Test {
public static void main(String args[]) {
Shape2D shapes[] = new Shape2D[10];
// shapes population
Point p1 = new Point(3, 4);
Point p2 = new Point();
Circle c1 = new Circle(p1, 5);
Rectangle r1 = new Rectangle(p2)
FilledCircle fc1 = new FilledCircle(p1, 8, 4)
...
shapes[0] = c1; shapes[1] = r1;
shapes[9] = fc1;
// shapes processing
// calculate the area of all shapes
double allArea = 0.0d;
for (int j = 0; j <shapes.length; j++)
// polymorphic behaviour of area()
allArea += shapes[j].area();
}

Ioan Salomie - OO Programming Techniques

62

Selective inheritance
Adapter classes
Abstract

methods

all methods are inherited


all methods should be approached
somehow
Adapter

classes in the inheritance

context
Alternative to abstract classes
The methods that are implemented with a
default behavior (common: empty
implementation body)
Solution to selective inheritance

Ioan Salomie - OO Programming Techniques

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

You might also like