You are on page 1of 22

Technical University of Cluj-Napoca

Computer Science Department

Object Oriented
Programming Techniques

Interface Techniques

Professor Ioan Salomie


Spring 2010

Ioan Salomie - Programming Techniques

Objective
Interface

related programming
techniques

Ioan Salomie - Programming Techniques

Interface - Introduction
Interface

declares a behaviour

Set of abstract methods


Classes

implementing interfaces
Multiplicity
Method implementation
all methods should be implemented

Interfaces

extending interfaces

Multiplicity

Ioan Salomie - Programming Techniques

Subtypes (revisited)
defines a type
Reference types in Java
Interface

class type,
array type or
interface type
The

complete subtype relations

Ioan Salomie - Programming Techniques

Subtypes (revisited)
Assume:

C, C1, C2 are classes


I, I1, I2 are interfaces
T, T1, T2 are types (references or primitives)
If

C1 extends C2 => C1 is a subtype of C2


If I1 extends I2 => I1 is a subtype of I2
If C implements I => C is subtype of I
For every I => I is a subtype of Object
For every T => T[] is a subtype of Object
If T1 is subtype of T2 => T1[] is a
subtype of T2[]
For any C that is not Object => C is
subtype of Object

Ioan Salomie - Programming Techniques

Interfaces and
polymorphic classes
Interfaces

can be used to define


polymorphic classes

class can implement multiple


interfaces
A class shows polymorphic behavior
(assumes different roles in different
contexts)

Ioan Salomie - Programming Techniques

Interfaces and polymorphic classes


Example
public interface StudentProcessing {
public double calculateAvgMarks();
public double getAvgMarks();
// other methods
}
public interface EmployeeProcessing {
public double calculateSalary();
public double getSalary();
// other methods
}
public class Student implements StudentProcessing {
protected double avgMarks;
public double calculateAvgMarks() {
// method implementation
}
public double getAvgMarks() {
// method implementation
}
}
public class Employee implements EmployeeProcessing {
protected double salary;
public double calculateSalary() {
// method implementation
}
public double getSalary() {
// method implementation
}
}
Ioan Salomie - Programming Techniques

Interfaces and polymorphic classes


Example
public class StudentEmployee implements
StudentProcessing, EmployeeProcessing {
protected double avgMarks;
protected double salary;
// other variables
public double calculateAvgMarks() {
// method implementation
}
public double getAvgMarks() {
// method implementation
}
public double calculateSalary() {
// method implementation
}
public double getSalary() {
// method implementation
}
}

Ioan Salomie - Programming Techniques

Interfaces and polymorphic classes


Example

StudentProcessing

Student

EmployeeProcessing

StudentEmployee

Employee

Ioan Salomie - Programming Techniques

Interfaces and polymorphic classes


Example
StudentEmployee

is subtype of both
StudentProcessing and
EmployeeProcessing

Instances

of StudentEmployee can
be viewed as students or employees

Ioan Salomie - Programming Techniques

10

Interfaces and polymorphic classes


Example
Instances

of StudentEmployee seen
as student

StudentProcessing[] students = new


StudentProcessing[SIZE];
students[0] = new Student();
students[1] = new StudentEmployee();
//
for(int i = 0; i <students.length; i++) {
students[i].getAvgMarks();
}

Ioan Salomie - Programming Techniques

11

Interfaces and polymorphic classes


Example
In

other context, instances of


StudentEmployee can be viewed as
employees

EmployeeProcessing[] employees = new


EmployeeProcessing[SIZE];
employees[0] = new Employee();
employees[1] = new StudentEmployee();
//
for(int i = 0; i <employees.length; i++) {
employees[i].getSalary();
}
Conclusion

A student employee can play two


different roles in two different
contexts
Ioan Salomie - Programming Techniques

12

Single and multiple


inheritance
Debated

topic in OO language

design
StudentEmployee class
implements two interfaces
inherits no implementation
Consequence

getAvgMarks()
distinct code in Student and
StudentEmployee classes

getSalary()
distinct code in Employee and
StudentEmployee classes

sources of inconsistency
Ioan Salomie - Programming Techniques

13

Single and multiple


inheritance

Case of true multiple inheritance

public class StudentProcessing {


public double getAvgMarks() { }
protected double avgMarks;
// other resources
}
public class EmployeeProcessing {
public double getSalary() { }
protected double salary;
// other resources
}
public class Student extends StudentProcessing {
// implementation of getAvgMarks() is inherited
// other resources
}
public class Employee extends EmployeeProcessing {
// implementation of getSalary() is inherited
// other resources
}
// the following is illegal Java code
public class StudentEmployee extends StudentProcessing,
EmployeeProcessing {
// implementation of getAvgMarks() and getSalary() is inherited
// other resources
}
Ioan Salomie - Programming Techniques

14

Single and multiple inheritance


Diamond shape inheritance

PersonProcessing

StudentProcessing

EmployeeProcessing

StudentEmployee

Ioan Salomie - Programming Techniques

15

Single and multiple inheritance


Diamond shape inheritance
public class PersonProcessing {
protected String name;
public String getName() { }
// other class resources
}
public class StudentProcessing extends PersonProcessing {
protected double avgMarks;
public double getAvgMarks() { }
// other resources
}
public class EmployeeProcessing extends PersonProcessing {
protected double salary;
public double getSalary() { }
// other resources
}
// the following is illegal Java code because multiple inheritance
public class StudentEmployee extends StudentProcessing,
EmployeeProcessing {
// implementation of getAvgMarks() and getSalary() is inherited
// other resources
}

Ioan Salomie - Programming Techniques

16

Single and multiple inheritance


Diamond shape inheritance
Main

problem

multiple inheritance on different inheritance


paths
Example

Question
How many 'name' a StudentEmployee object has?

Questions
Which copy is accessed?
Can we access both copies?

C++ keyword virtual


The syntactic representation and use of
multiple inheritance gets complicated

Ioan Salomie - Programming Techniques

17

Single and multiple inheritance


Java solution - implementation reuse
through delegation
Implementation

reuse in Java

Simple inheritance plus


Delegation technique

Ioan Salomie - Programming Techniques

18

Single and multiple inheritance


Java solution - implementation reuse
through delegation

StudentProcessing

EmployeeProcessing

StudentImpl

Student

EmployeeImpl

StudentEmployee

Employee

Ioan Salomie - Programming Techniques

19

Single and multiple inheritance


Java solution - implementation reuse
through delegation
public interface StudentProcessing {
public double getAvgMarks();
public double calculateAvgMarks();
}
public interface EmployeeProcessing {
public double getSalary();
public double calculateSalary();
}
public class StudentImpl implements StudentProcessing {
protected double avgMarks;
public double calculateAvgMarks() { }
public double getAvgMarks() { }
}
public class EmployeeImpl implements EmployeeProcessing {
protected double salary;
public double calculateSalary() { }
public double getSalary() { }
}
public class Student extends StudentImpl {
// methods getAvgMarks() and calculateAvgMarks() are inherites
// avgMarks field is inherited
}
public class Employee extends EmployeeImpl {
// methods getSalary() and calculateSalary() are inherites
// salary field is inherited
}

Ioan Salomie - Programming Techniques

20

Single and multiple inheritance


Java solution - implementation reuse
through delegation
public class StudentEmployee implements
StudentProcessing, EmployeeProcessing {
protected StudentImpl studentImpl;
protected EmployeeImpl employeeImpl;
public StudentEmployee() {
studentImpl = new StudentImpl();
employeeImpl = new EmployeeImpl();
// other constructor statements
}
public double getAvgMarks() {
// delegation is used
return studentImpl.getAvgMarks();
}
public double getSalary() {
// delegtion is used
return employeeImpl.getSalary();
}
// same for calculateAvgMarks() andcalculateSalary()
}
Ioan Salomie - Programming Techniques

21

Single and multiple inheritance


Java solution - implementation reuse
through delegation
Methods

using delegation

getAvgMarks() and getSalary()


calculateAvgMarks() and
calculateSalary()
Each method delegates its task to
another object
Reuse

through delegation
Consistency is preserved

Ioan Salomie - Programming Techniques

22

Interfaces and name


collisions
Sources

for name collisions

A class may
extend one class
implement multiple interfaces

An interface may
extend multiple interfaces

Methods with

the same name => needs

resolve rules
different signatures => overloaded
same signature && same return type =>
same method
same signature && different return types =>
compile error
same signature && same return type but
throw different exceptions => same method,
union of throw lists
Ioan Salomie - Programming Techniques

23

Interfaces and name collisions


Example
public interface A{
public void m1(int iVal);
public void m2(int iVal);
public void m3(int iVal);
public void m4(int iVal) throws Ex1;
}
public interface B{
public void m1(double dVal);
public void m2(int iVal);
public int m3(int iVal);
public void m4(int iVal) throws Ex2;
}
public class C implements A, B { }
Question
how to implement the methods in class C?
Ioan Salomie - Programming Techniques

24

Interfaces and name collisions


Example
The

approach for constants

public interface X {
static final int c = ;
}
public interface X {
static final double c = ;
}
public class C implements X, Y {
void aMethod() {
X.c // the int constant
Y.c // the double constant
}
}
two separate constants c (one int, one double)
Ioan Salomie - Programming Techniques

25

Marker interfaces
public interface M {}
public class C implements M { }
M

is an empty interface
M and C - subtype relationship
Class C is marked as having a certain
property
The property is given (highlighted) by the
name of the interface
Example

of such interface

Clonable
It distinguishes the classes that can be cloned
of those that cannot be cloned

Ioan Salomie - Programming Techniques

26

Classes implementing
multiple interfaces

Flat approach

interface GeometricCalculations {
double calcArea();
double calcPerimeter();
}
public class Circle implements
GeometricCalculations, Comparable, Serializable {
//
public int compareTo(Object o) { }
public double calcArea() { }
public double calcPerimeter() { }
}

Ioan Salomie - Programming Techniques

27

Classes implementing
multiple interfaces

Hierarchical approach

interface Composite extends


GeometricCalculations, Comparable,
Serializable { }
public class Circle implements Composite
//
public int compareTo(Object o) { }
public double calcArea() { }
public double calcPerimeter() { }
}

Ioan Salomie - Programming Techniques

28

Mixin
Modify

existing classes to
implement certain interfaces
additional facilities to its basic
functionality
Example: Serializable, Comparable,
Cloning

Ioan Salomie - Programming Techniques

29

Interfaces vs. Abstract classes


public abstract class AC {
public abstract void m();
}
public interface IF {
public void m();
}
Common

feature

Both define a contract that must be


implemented by a class
A concrete class that extends AC must
define m()
A class that implements IF must
define m()
Important

differences

Ioan Salomie - Programming Techniques

30

Interfaces vs. Abstract classes


The

content of the two structures

Abstract classes

Methods
Instances
Constructors
A partial implementation

Interfaces
Public methods
Constants
No implementation allowed

Features

An interface
Interface inheritance
Allow for multiple interface extensions
A class can implement multiple interfaces

A class
Can only extend ("implementation inheritance") one
other class.
Ioan Salomie - Programming Techniques

31

Interfaces vs. Abstract classes


Comparison

criteria

system evolution
able or can do vs. is-a
homogeneity vs. heterogeneity
speed
third party functionality

Ioan Salomie - Programming Techniques

32

Interfaces vs. Abstract classes


System evolution
Consider

two operational systems

one uses the AC


one uses IF
Scenario

adding a new method m1()


Adding the method to AC
Adding the method to IF

Ioan Salomie - Programming Techniques

33

Interfaces vs. Abstract classes


System evolution
Abstract

class approach

m1() can be implemented


abstract class is partial implemented
public abstract class AC {
public abstract void m();
public void m1() { // implementation }
}
AC subclasses
they can use m1 as it is defined in the AC

they can override it


AC

are useful when you need to provide a


partial implementation

Ioan Salomie - Programming Techniques

34

Interfaces vs. Abstract classes


System evolution
Interface

approach
public interface IF {
public void m();
public void m1();
}
All

classes that implemented IF should


implement m1()
The existing system is broken (invalidated)
Changing the interfaces will break a lot of
code

Conclusions

abstract classes are easier to evolve over time


interfaces are better choices than abstract
classes providing you will not modify it
when designing interfaces - make sure they
would not change very often and very soon

Ioan Salomie - Programming Techniques

35

Interfaces vs. Abstract classes


able or can do vs. is-a
Interface

not describing class main role


describe the peripheral class abilities
Example
Bicycle may implement Recyclable
Many other (unrelated) classes may implement
Recyclable

Abstract

class

defines the core identity of its descendants


Example class Dog
Implemented interfaces

Specifies what a class can do


Doesnt specify what a class is.

Ioan Salomie - Programming Techniques

36

Interfaces vs. Abstract classes


homogeneity vs. heterogeneity
Interfaces
All the various implementations share is
the method signatures
New implementations no common code
with previous implementations
Start from scratch
Freedom to implement a totally new
internal design
Abstract

class

All various implementations are all of a


kind and share a common status and
behavior
AC should be used as it is (good or bad)
Imposes a certain structure to the new
implemented subclasses (homogeneous
subclasses)

Ioan Salomie - Programming Techniques

37

Interfaces vs. Abstract classes


speed
Interface

Slow
Requires extra indirection to identify
the corresponding method in the actual
class
Modern JVMs new ways to reduce
this speed penalty
Abstract

class

Fast

Ioan Salomie - Programming Techniques

38

Interfaces vs. Abstract classes


Third party functionality
Interface

Interface implementation may be


added to any existing third party
class
Abstract

class

Third party class must be rewritten


to extend from the abstract class

Ioan Salomie - Programming Techniques

39

Interfaces and Abstract classes

Combining Interfaces and Abstract Classes


Example - Java Collection Framework

interface List {
int size();
boolean isEmpty();
// other methods
}
abstract class AbstractList implements List {
public abstract int size();
public boolean isEmpty() {
return size() == 0;
}
// other class elements
}
class ArrayList extends AbstractList {
public int size() { }
// other class elements
}
Ioan Salomie - Programming Techniques

40

Interfaces and Abstract classes


<<interface>>
Collection

Abstract
Collection

<<interface>>
List

AbstractList

ArrayList

AbstractSequential List

Vector

LinkedList

<<interface>>
Serializable
<<interface>>
Clonable

Ioan Salomie - Programming Techniques

41

Interfaces and Abstract classes


Level

0 - Top hierarchy

interfaces such as Collection, List


describe contracts (behavior specification)
Level

Abstract classes such as AbstractList


provide partial implementation
Level

concrete classes such as ArrayList or Vector


define all abstract methods that are not
already defined

Ioan Salomie - Programming Techniques

42

Interfaces and Abstract classes


Benefits

of programming in terms of
interfaces
Much of the implementation is already
done in superclasses
Easy switch between implementations
Develop parallel implementations

Ioan Salomie - Programming Techniques

43

You might also like