Encapsulation - · PDF fileEncapsulation • Encapsulation – grouping of subprograms...

32
Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen TUT Pervasive Computing 1 Encapsulation • Encapsulation grouping of subprograms and the data they manipulate Information hiding abstract data types implementation of the type is hidden from the user variables of the type can be declared variables of the type can be used via the operations defined for the type • Mechanisms modules, packages, classes nested subprograms, file system Imperative programming • abstraction via subprograms Modular programming • data abstraction

Transcript of Encapsulation - · PDF fileEncapsulation • Encapsulation – grouping of subprograms...

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 1

Encapsulation

• Encapsulation– grouping of subprograms and the data they manipulate

• Information hiding– abstract data types

• implementation of the type is hidden from the user• variables of the type can be declared• variables of the type can be used via the operations defined for

the type• Mechanisms

– modules, packages, classes– nested subprograms, file system

Imperative programming• abstraction via subprogramsModular programming• data abstraction

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 2

Module vs. class

• Module– static structure– interface and implementation– scope

• no code is generated from a module

• Class– dynamic module

• it is possible to create run time instances

– corresponds to a type

• program modularization(division into parts)

• separate compilation

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 3

Module definition and use(Modula-2)

DEFINITION MODULE Stack;PROCEDURE Push ( X: CARDINAL );PROCEDURE Pop ( ): CARDINAL;VAR Empty, Error: BOOLEAN;

END Stack;

FROM Stack IMPORT Push;...Push ( 3 );

IMPORT Stack;...Stack.Push ( 3 );

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 4

Module implementation (Modula-2)

IMPLEMENTATION MODULE Stack;CONST N = 100;TYPE Index = [ 0..N ];VAR Top: Index;

S: ARRAY Index OF CARDINAL;PROCEDURE Push ( X: CARDINAL );

...PROCEDURE Pop ( ): CARDINAL;

...

BEGINError := FALSE;Empty := TRUE;Top := 0;

END Stack;

BEGIN (* Push *)IF Top = N THEN

Error := TRUE;ELSE

Top := Top + 1;S [ Top ] := X;Empty := FALSE;

END;END Push;

BEGIN (* Pop *)IF Top = 0 THEN Error := TRUE;ELSE

Top := Top – 1;IF Top = 0 THEN Empty := TRUE END;RETURN S [ Top + 1 ];

END;END Pop;

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 5

Module use (Modula-2)• Deficiencies of the

example:– user can change the

values of variablesError and Empty

– it is not possible tocreate several stacks

MODULE StackUser;IMPORT Stack;...C: CARDINAL;...BEGIN

...Stack.Push ( 5 );...C := Stack.Pop ( );...

END StackUser;

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 6

Improving the example• Using module as a ”manager” for a type (e.g. stack)• This requires:

– an operation to create (initialize) a stack instance– an operation to delete a stack instance– for each operation an additional parameter to tell which

stack instance the operation is applied to• Stack type is defined as an opaque type

– restrictions to variables of this type• they can be passed as parameters to module operations• they can be assigned and their equality can be tested

– corresponds to an abstract data type

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 7

Definition of an abstract data type

DEFINITION MODULE StackManager;TYPE Stack;PROCEDURE Push ( S: Stack, X: CARDINAL );PROCEDURE Pop ( S: Stack ): CARDINAL;PROCEDURE Empty ( S: Stack ): BOOLEAN;PROCEDURE Initialize ( VAR S: Stack );

END StackManager;Restrictions for an opaque type (in Modula-2):• it must be a pointerØ size is always the same: recompilation is minimized

Modula-2:

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 8

IMPLEMENTATION MODULE StackManager;FROM Storage IMPORT ALLOCATE;CONST N = 100;TYPE Index = [ 1..N ];

StackRec = RECORDTop: Index;StackArr: ARRAY Index OF CARDINAL

END;Stack = POINTER TO StackRec;

PROCEDURE Pop ( S: Stack ): CARDINAL;BEGIN

IF S^.Top > 0 THENS^.Top := S^.Top – 1;RETURN S^.StackArr [ S^.Top + 1 ]

ENDEND Pop;...PROCEDURE Initialize ( VAR S: Stack );BEGIN

NEW ( S ); S^.Top := 0END Initialize;

END StackManager;

Modula-2:

Implementationof an abstractdata type

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 9

Use of an abstract data type...VAR S1, S2: StackManager.Stack;

I: CARDINAL;...StackManager.Initialize ( S1 );StackManager.Initialize ( S2 );...StackManager.Push ( S1, 2 );StackManager.Push ( S2, 3 );...IF NOT StackManager.Empty ( S1 ) THEN

I := StackManager.Pop ( S1 );END;...

Modula-2:

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

Shortcomings of modules

• It is possible to declare several types insidethe same module

• Modules do not totally fulfil the encapsulationintent (i.e. tight cohesion between the type andits operations)

• An operation in a module is an externalobject, to which a certain instance (e.g. stack)is passed as a parameter

• Do not support inheritance (and reuse)

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 11

Classes• Put together those objects that have the same

behavior• Support abstract data types better than modules

– modules can be used by importing them– classes can be used in variable declarations like types

• Class hierarchy (inheritance)– behavior of the superclass instances is copied to be part

of the behavior the subclass instances– multiple inheritance vs. single inheritance

• Meta class– a class described as a class

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 12

Comparison ofmodules and classes

class Complex {public:

Complex ( );Complex ( float, float );virtual ~Complex ( );int isZero ( );

private:float re;float im;

};

package Complex isprocedure Initialize ( r, i: Float );function IsZero return Boolean;

privatere: Float;im: Float;

end Complex; package ComplexManager istype Complex is private;procedure Initialize ( c: in out Complex;

r: in Float; i: in Float );function IsZero ( c: Complex ) return Boolean;

privatetype Complex is record

re: Float;im: Float;

end record;end ComplexManager;

with Complex;…Complex.Initialize ( 1.0, 2.0 );if Complex.IsZero then …

c1: Complex;c2: Complex ( 1.0, 2.0 );if ( c1.IsZero ( ) ) …

with ComplexManager;use ComplexManager;…c1, c2 : Complex;Initialize ( c1, 0.0, 0.0 );Initialize ( c2, 1.0, 2.0 );if IsZero ( c1 ) then …

C++ Ada

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 13

Design issues for object-orientedlanguages• Exclusivity of objects

– consistency vs. inefficiency• Are subclasses subtypes?

– consistency between subclasses andsuperclasses

• Implementation and interfaceinheritance– dependency vs. inefficiency

• Single and multiple inheritance• Dynamic/static binding, dynamic/static typing• Allocation and deallocation of objects

int second ( ) {int temp = top ( );pop ( );int temp_result = top ( );push ( temp );return temp_result;

}

Vector v = new Vector ( );v.addElement ( new Integer ( 10 ) );

Java:

C++:

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 14

Inheritance choices (C++)• Implementation inheritance

– implementation defined asprotected in the superclass

• Interface inheritance– implementation defined as private

in the superclass• Subclass is not a subtype

– private features of the superclassare not visible in subclasses

– private inheritance

class BaseClass {private:

int a;float x;

protected:int b;float y;

public:int c;float z;

};

class SubClass1: public BaseClass { ... };class SubClass2: private BaseClass { ... };

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 15

Influences ofinheritance (C++)

linked_list+ insert_at_head ( int )+ insert_at_tail ( int )+ remove_at_head ( )

+ push ( int )+ pop ( )

queue+ enqueue ( int )+ dequeue ( )void push ( int i ) {

insert_at_head ( i );}

void enqueue ( int i ) {insert_at_tail ( i );

}int pop ( ) {return remove_at_head ( i );

}int dequeue ( ) {

return remove_at_head ( i );}

private-inheritance:• natural in this case• subclass is not a subtype stack

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 16

Object lifetime• Creation

– constructors (zero, one, or several)• selecting a constructor (overloading)• execution order of the constructors

– objects as references (e.g. Java, Simula, Smalltalk)• explicit creation (constructor call)

– objects as values (e.g. C++, Oberon, Ada95)• creation can be implicit during declaration elaboration

• Deletion– either with explicit command or automatically– languages with automated garbage collection do not

necessarily need destructors

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 17

Objects as values or as references

foo a;foo a ( 10 );

foo a;a = new foo ( );

foo a;foo c = a;

foo a, c;c = a;

Initialization: Assignment:

int a;

foo a = new foo ( );

foo::foo ( foo& ) foo::operator= ( foo& )

C++: Java:foo::foo ( )

foo::foo ( int )

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 18

Object creation (C++)• Automatic object

– created at declaration elaboration, deleted when exitingthe block

• Static object– created when execution starts and deleted when it

terminates• Dynamic object

– created and deleted with explicit command• Member object

– created and deleted with the object whose member themember object is

{ ... classC x; ... }

classC x;static classC x; or in main:

x = new classC; ... delete x;

class C1 { ... classC x; ... }

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

Object creation (in general)

• Stack memory allocation for objects: sizemust be known during compilation

• Inheritance: objects that look like baseclass objects can really be of derived class!So size depends on situation

• In many languages memory for objects isalways allocated from the heap

• Same goes for member objects in a class

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 20

Operation binding• Dynamic binding = run time binding

– enables polymorphism that is typical for object orientation– implemented via virtual operations

• Virtual operation– operation to be called is selected on the basis of the object’s current

class• Polymorphism

– in object-oriented languages• superclass instance can be replaced with a subclass instance

– in general• a named object can be replaced with another named object

– genericity, templates (parametric polymorphism)– overloading (ad hoc polymorphism)

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 21

Static and dynamic bindingclass person { ... }class student: public person { ... }class professor: public person { ... }

student s;professor p;...person *x = &s;person *y = &p;

s.contact ( ); // student::contact ( )p.contact ( ); // professor::contact ( )

x->contact ( ); // ??y->contact ( ); // ??

Static binding redefine• method is selected on the basis of the variable typeDynamic binding override• method is selected on the basis of the object’s class

contact-operation is defined in all three classes

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 22

Static and dynamic binding inprogramming languages

• Dynamic binding for all operations– Smalltalk, Modula-3

• Dynamic binding as default– Java, added with final definition– Eiffel, added with frozen definition

• Static binding as default– C++, added with virtual definition– Simula, added with virtual definition– Ada95, class wide types used as formal parameters

Operations cannot beoverridden insubclasses

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 23

Implementation of object orientation• Features in memory

– class resembles a record (especially in C++)• CIR (class instance record)

– static structure• each feature can be found by evaluating the offset of the feature

– subclass adds its own features after the CIR of thesuperclass

• Dynamically bound operations– references to these operations can be found from CIR– list of operations that can be bound dynamically

• virtual method table (VMT, vtable)

informationabout an object

informationabout a class

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 24

Implementation of object orientation• Dynamically bound operations in dynamically

typed object oriented languages– each class has a method parser function– method parser receives method name and parameters and

decides what code to call– if parser finds no suitable method, it gives a run-time

error– if subclass parser finds no suitable method, it calls base

class parser(s) before giving an error– slower than static methods, but more flexible– in some languages, programmer may write custom

method parsers for a class

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 25

Implementing classes anddynamically bound operations

class Foo {int x;double y;char z;

public:virtual void k ( ... );virtual int l ( ... );virtual void m ( ... );virtual double n ( ... );...

} f;

n

kl

mx

y

z

CIR of f VMT of Foo

code of m

code of kcode of l

code of n

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 26

Implementing single inheritance

class Bar: public Foo {int w;

public:void m ( ... ); // overridevirtual double s ( ... );virtual char *t ( ... );...

} b;

n

kl

mx

y

z

CIR of b VMT of Bar

code of Bar::m

w

st

code of Foo::ncode of Bar::s

code of Foo::kcode of Foo::l

code of Bar::t

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 27

class foo { ... }class bar: public foo { ... }...foo f;bar b;foo *fr;bar *br;...fr = &b; // ok: the first parts of

// data store and VMT// of b are assigned

br = &f; // error: f is lacking the// end parts

br = dynamic_cast<bar*> ( fr );

class foo ...class bar inherit foo ......f: foo;b: bar;...f := b; -- okb ?= f; -- assignment

-- succeeds, if f refers-- to b object,-- otherwise nil is-- assigned

Backward assignmentReverse assignment

Assignment compatibility

C++

Eiffel

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 28

Choices for multiple inheritance

• Non-repeated multiple inheritance– inherited superclasses are separate in the class

hierarchy• Repeated multiple inheritance

– replicated multiple inheritance– shared multiple inheritance

• diamond inheritance

B C

D

A

D

A

B C

B C

A

D

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 29

Implementing multiple inheritance

• Name conflict– inherited classes may have features of the same name– how to refer to the features of all the superclasses

• C++: operator ::• Eiffel: renaming

• Shared inheritance (diamond inheritance)– by which way does D inherit features of A– any feature inherited from A can be redefined in B or C

D

A

B C

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 30

Non-repeated multiple inheritance

Bfields

Cfields

D (only)fields

B operations

D (only) operations

C operations

CIR of D obj. VMT of D (D/B part)

VMT of D (C part)

D view,B view

C view

B C

D

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 31

Replicated multiple inheritance

B (only)fields

C (only)fields

D (only)fields

B (only) operations

D (only) operations

C (only) operations

CIR of D obj.VMT of D (D/B part)

VMT of D (C part)

D view,B view,B::A view

C view,C::A view

B::Afields

C::Afields

B::A operations

C::A operations

A *a;B *b;D *d;...a = d;...b = d;a = b;

OK

/..

D

A

B C

A

Principles of programming languagesMaarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing 32

Shared multiple inheritance

B (only)fields

C (only)fields

D (only)fields

B operations

D operations

CIR of D obj.VMT of D (D/B part)

VMT of D (C part)

D view,B view

C view

A view

A fields

C operations

A operationsVMT of D (A part)

D

A

B C