cs2403 programming languages support for object-oriented programming

51
CS2403 Programming Languages Support for Object- Oriented Programming Chung-Ta King Department of Computer Science National Tsing Hua University (Slides are adopted from Concepts of Programming Languages, R.W. Sebesta)

Upload: cerise

Post on 03-Feb-2016

109 views

Category:

Documents


0 download

DESCRIPTION

CS2403 Programming Languages Support for Object-Oriented Programming. Chung-Ta King Department of Computer Science National Tsing Hua University. (Slides are adopted from Concepts of Programming Languages , R.W. Sebesta). Software Productivity. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: CS2403 Programming Languages Support for Object-Oriented Programming

CS2403 Programming Languages

Support for Object-Oriented Programming

Chung-Ta KingDepartment of Computer ScienceNational Tsing Hua University

(Slides are adopted from Concepts of Programming Languages, R.W. Sebesta)

Page 2: CS2403 Programming Languages Support for Object-Oriented Programming

2

Software Productivity

Pressure on software productivity vs. continual reduction in hardware cost

Productivity increases can come from reuse Abstract data types (ADTs) for reuse? Mere ADTs are not enough

ADTs are difficult to reuse—always need changes for new uses, e.g., circle, square, rectangle, ...

All ADTs are independent and at the same level hard to organize program to match problem space

More, in addition to ADTs, are needed

Page 3: CS2403 Programming Languages Support for Object-Oriented Programming

3

What Are Needed?

Given a collection of related ADTs, need to factor out their commonality and put it in a new type abstractionThe collection of ADTs then inherit from the

new type and add their ownclass Shape { private: int x; int y; public: Shape(int a, int b);

... virtual void draw(); };

class Circle: public Shape { private: int radius; public: Circle(int x1, y2, r1); ... void draw(); };

Page 4: CS2403 Programming Languages Support for Object-Oriented Programming

4

What Are Needed? (cont.)

For classes in an inheritance relationship, a method call may need to be bound to a specific object of one of the classes at run timeShape *shape_list[3]; // array of shape objects shape_list[0] = new Circle; shape_list[1] = new Square; shape_list[2] = new Triangle; for(int i = 0; i < 3; i++){ shape_list[i].draw();

} Polymorphism and dynamic binding

Dynamic Class Loading for C++ on Linux (http://www.linuxjournal.com/article/3687)

Page 5: CS2403 Programming Languages Support for Object-Oriented Programming

5

Object-Oriented Programming

An object-oriented language must provide supports for three key features:Abstract data typesInheritance: the central theme in OOP and

languages that support itPolymorphism and dynamic binding

What does it mean in a pure OO program, where x, y, and 3 are objects?

y = x + 3;

Page 6: CS2403 Programming Languages Support for Object-Oriented Programming

6

Outline

Object-Oriented Programming (Sec. 12.2) Design Issues for OO Languages (Sec. 12.3) Support for OOP (Sec. 12.4 ~ 12.9)

SmalltalkC++JavaC#Ada 95Ruby

Implementation of OO Constructs (Sec. 12.10)

Page 7: CS2403 Programming Languages Support for Object-Oriented Programming

7

Object-Oriented Concepts

ADTs are usually called classes, e.g. Shape Class instances are called objects, e.g. shape_list[0]

A class that inherits is a derived class or a subclass, e.g. Circle, Square

The class from which another class inherits is a parent class or superclass, e.g. Shape

Subprograms that define operations on objects are called methods, e.g. draw()

Page 8: CS2403 Programming Languages Support for Object-Oriented Programming

8

Object-Oriented Concepts (cont.)

Calls to methods are called messages, e.g. shape_list[i].draw();

Object that made the method call is the client

The entire collection of methods of an object is called its message protocol or message interface

Messages have two parts--a method name and the destination object

In the simplest case, a class inherits all of the entities of its parent

Page 9: CS2403 Programming Languages Support for Object-Oriented Programming

9

Inheritance

Allows new classes defined in terms of existing ones, i.e., by inheriting common parts

Can be complicated by access controls to encapsulated entitiesA class can hide entities from its subclasses

(private)A class can hide entities from its clientsA class can also hide entities for its clients while

allowing its subclasses to see them A class can modify an inherited method

The new one overrides the inherited oneThe method in the parent is overridden

Page 10: CS2403 Programming Languages Support for Object-Oriented Programming

10

Inheritance (cont.)

There are two kinds of variables in a class:Class variables - one/classInstance variables - one/object, object state

There are two kinds of methods in a class:Class methods – accept messages to the classInstance methods – accept messages to

objects Single vs. multiple inheritance One disadvantage of inheritance for reuse:

Creates interdependencies among classes that complicate maintenance

Page 11: CS2403 Programming Languages Support for Object-Oriented Programming

11

Dynamic Binding

A polymorphic variable can be defined in a class that is able to reference (or point to) objects of the class and objects of any of its descendantsShape *shape_list[3]; // array of shapesshape_list[0] = new Circle; shape_list[1] = new Square; shape_list[2] = new Triangle; for(int i = 0; i < 3; i++){ shape_list[i].draw();

}

Page 12: CS2403 Programming Languages Support for Object-Oriented Programming

12

Dynamic Binding

When a class hierarchy includes classes that override methods and such methods are called through a polymorphic variable, the binding to the correct method will be dynamic, e.g.,

shape_list[i].draw(); Allows software systems to be more easily

extended during both development and maintenance, e.g., new shape classes are defined later

Page 13: CS2403 Programming Languages Support for Object-Oriented Programming

13

Dynamic Binding (cont.)

An abstract method is one that does not include a definition (it only defines a protocol)

An abstract class is one that includes at least one virtual methodAn abstract class cannot be instantiatedclass Shape {

private: int x; int y; public: ... virtual void draw(); };

class Circle: public Shape { private: int radius; public: ... void draw() {...}; };

Page 14: CS2403 Programming Languages Support for Object-Oriented Programming

14

Outline

Object-Oriented Programming (Sec. 12.2) Design Issues for OO Languages (Sec. 12.3) Support for OOP (Sec. 12.4 ~ 12.9)

SmalltalkC++JavaC#Ada 95Ruby

Implementation of OO Constructs (Sec. 12.10)

Page 15: CS2403 Programming Languages Support for Object-Oriented Programming

15

Design Issues for OOP Languages

The exclusivity of objects Are subclasses subtypes? Type checking and polymorphism Single and multiple inheritance Object allocation and deallocation Dynamic and static binding Nested classes Initialization of objects

Page 16: CS2403 Programming Languages Support for Object-Oriented Programming

16

The Exclusivity of Objects

Option 1: Everything is an objectAdvantage: elegance and purityDisadvantage: slow operations on simple objects

Option 2: Add objects to existing typing systemAdvantage: fast operations on simple objectsDisadvantage: confusing typing (2 kinds of entities)

Option 3: Imperative-style typing system for primitives and everything else objectsAdvantage: fast operations on simple objects and a

relatively small typing systemDisadvantage: still confusing by two type systems

Page 17: CS2403 Programming Languages Support for Object-Oriented Programming

17

Are Subclasses Subtypes?

Does an “is-a” relationship hold between a parent class object and an object of subclass?If a derived class is-a parent class, then objects of

derived class behave same as parent class objectsubtype small_Int is Integer range 0 .. 100;Every small_Int variable can be used anywhere Integer variables can be used

A derived class is a subtype if methods of subclass that override parent class are type compatible with the overridden parent methods A call to overriding method can replace any call to

overridden method without type errors

Page 18: CS2403 Programming Languages Support for Object-Oriented Programming

18

Type Checking and Polymorphism

Polymorphism may require dynamic type checking of parameters and the return valueDynamic type checking is costly and delays

error detection If overriding methods are restricted to

having the same parameter types and return type, the checking can be static

Page 19: CS2403 Programming Languages Support for Object-Oriented Programming

19

Single and Multiple Inheritance

Multiple inheritance allows a new class to inherit from two or more classes

Disadvantages of multiple inheritance:Language and implementation complexity: if

class C needs to reference both draw() methods in parents A and B, how to do? If A and B in turn inherit from Z, which version of Z entry in A or B should be ref.?

Potential inefficiency: dynamic binding costs more with multiple inheritance (but not much)

Advantage: Sometimes it is quite convenient and valuable

Page 20: CS2403 Programming Languages Support for Object-Oriented Programming

20

Object Allocation and Deallocation

From where are objects allocated?If behave like ADTs, can be allocated from

anywhereAllocated from the run-time stackExplicitly created on the heap (via new)

If they are all heap-dynamic, references can be uniform thru a pointer or reference variableSimplifies assignment: dereferencing can be implicit

If objects are stack dynamic, assignment of subclass B’s object to superclass A’s object is value copy, but what if B is larger in space?

Is deallocation explicit or implicit?

Page 21: CS2403 Programming Languages Support for Object-Oriented Programming

21

Dynamic and Static Binding

Should all binding of messages to methods be dynamic?If none are, you lose the advantages of

dynamic bindingIf all are, it is inefficient

Alternative: allow the user to specify

Page 22: CS2403 Programming Languages Support for Object-Oriented Programming

22

Nested Classes

If a new class is needed by only one class, no reason to define it to be seen by other classesCan the new class be nested inside the class

that uses it?In some cases, the new class is nested inside a

subprogram rather than directly in another class

Other issues:Which facilities of the nesting class should be

visible to the nested class and vice versa

Page 23: CS2403 Programming Languages Support for Object-Oriented Programming

23

Initialization of Objects

Are objects initialized to values when they are created?Implicit or explicit initialization

How are parent class members initialized when a subclass object is created?

Page 24: CS2403 Programming Languages Support for Object-Oriented Programming

24

Outline

Object-Oriented Programming (Sec. 12.2) Design Issues for OO Languages (Sec. 12.3) Support for OOP (Sec. 12.4 ~ 12.9)

SmalltalkC++JavaC#Ada 95Ruby

Implementation of OO Constructs (Sec. 12.10)

Page 25: CS2403 Programming Languages Support for Object-Oriented Programming

25

Inheritance in C++

InheritanceA class need not be the subclass of any classAccess controls for members are

Private: accessible only from within other members of the same class or from their friends.

Protected: accessible from members of the same class and from their friends, but also from members of their derived classes.

Public: accessible from anywhere that object is visible Multiple inheritance is supported

If two inherited members with same name, they can both be referenced using scope resolution operator

Page 26: CS2403 Programming Languages Support for Object-Oriented Programming

26

Inheritance in C++ (cont.)

In addition, the subclassing process can be declared with access controls (private or public), which define potential changes in access by subclassesPrivate derivation: inherited public and

protected members are private in the subclasses members in derived class cannot access to any member of the parent class

Public derivation: public and protected members are also public and protected in subclasses

Page 27: CS2403 Programming Languages Support for Object-Oriented Programming

27

Inheritance Example in C++

class base_class { private: int a; float x; protected: int b; float y; public: int c; float z; };class subclass_1 : public base_class {…};// b, y protected; c, z publicclass subclass_2 : private base_class {…};// b, y, c, z private; no access by derived

Page 28: CS2403 Programming Languages Support for Object-Oriented Programming

28

Inheritance Example 2 in C++

class base{ int x; public: void setx(int n) {x = n;} void showx(void) {cout << x << "\n“;}}; class derived : private base{ int y; public: void setxy(int n) {y = n; x = n; } showxy(void) { cout<<x<<"\n"; cout<<y<<"\n"; } };

Where are the errors?

(http://www.umsl.edu/~subramaniana/private_inherit.html)

Page 29: CS2403 Programming Languages Support for Object-Oriented Programming

29

Inheritance Example 2 (cont.)

class base{ int x; public: void setx(int n) {x = n;} void showx(void) {cout<<x<< "\n"; } };class derived : private base{ int y; public: void setxy(int n, m) {setx(n); y = m; } void showxy(void) {showx(); cout<<y; }}; (http://www.umsl.edu/~subramaniana/private_inherit.html)

Page 30: CS2403 Programming Languages Support for Object-Oriented Programming

30

Reexportation in C++

A member that is not accessible in a subclass (because of private derivation) can be visible there using scope resolution operator (::), e.g.,class subclass_3 : private base_class { base_class :: c; ... }

One motivation for using private derivationA derived class adds some new members, but

does not want its clients to see members of the parent class, even though they had to be public in the parent class definition

Page 31: CS2403 Programming Languages Support for Object-Oriented Programming

31

Another Example in C++

class single_LL { private: class node { public: node *link; int contents; }; node *head; public: single_LL() {head = 0}; void insert_at_head(int); void insert_at_tail(int); int remove_at_head(); int empty(); }

Page 32: CS2403 Programming Languages Support for Object-Oriented Programming

32

Another Example in C++ (cont.)

class stack: public single_LL { public: stack() {}; void push(int value) { single_LL::insert_at_head(value); }; int pop() { return single_LL::remove_at_head();};};class queue: public single_LL { ... enqueue(int value) ... dequeue() ...};

Page 33: CS2403 Programming Languages Support for Object-Oriented Programming

33

Problem with Public Derivation

Clients of stack can access all of the public members of the parent class, single_LL, including insert_at_tail not desirablePublic derivation is used when one wants

subclass to inherit the entire interface of the base class

Let subclass inherit only the implementation of the base class and make it not subtype of the parent

Page 34: CS2403 Programming Languages Support for Object-Oriented Programming

34

Private Derivation in C++

class stack2: private single_LL { public: stack2() {}; void push(int value) { single_LL::insert_at_head(value); }; int pop() { return single_LL::remove_at_head();}; single_LL::empty(); //reexport};

Page 35: CS2403 Programming Languages Support for Object-Oriented Programming

35

Private Derivation in C++ (cont.)

class queue2: private single_LL { public: queue2() {}; void enqueue(int value) { single_LL::insert_at_tail(value); }; int dequeue() { return single_LL::remove_at_head();}; single_LL::empty(); //reexport};

Page 36: CS2403 Programming Languages Support for Object-Oriented Programming

36

Dynamic Binding in C++

A method can be defined to be virtual, and can be called through polymorphic variables and dynamically bound to messagesA pure virtual function has no definition at all

A class that has at least one pure virtual function is an abstract classclass Shape {

public: ... virtual void draw()=0; };

class Circle: public Shape { public:

... void draw() {...}; };

Page 37: CS2403 Programming Languages Support for Object-Oriented Programming

37

Dynamic Binding in C++ (cont.)

square* sq = new square;rectangle* rect = new rectangle;shape* shape_ptr;shape_ptr = sq; shape_ptr->draw(); // dynamically boundrect = sq;rect->draw(); // statically boundsquare sq1; // sq1 on stackrectangle rect1;rect1 = sq1; // copy data member valuesrect1.draw();

Page 38: CS2403 Programming Languages Support for Object-Oriented Programming

38

Support for OOP in C++

EvaluationC++ provides extensive access controls

(unlike Smalltalk)C++ provides multiple inheritanceProgrammer must decide at design time which

methods will be statically or dynamically boundStatic binding is faster!

Smalltalk type checking is dynamic (flexible, but somewhat unsafe and is ~10 times slower due to interpretation and dynamic binding

Page 39: CS2403 Programming Languages Support for Object-Oriented Programming

39

Support for OOP in Java

Focus on the differences from C++ General characteristics

All data are objects except the primitive typesAll primitive types have wrapper classes to store data

value, e.g., myArray.add(new Integer(10));All classes are descendant of the root class, ObjectAll objects are heap-dynamic, are referenced through

reference variables, and most are allocated with newNo destructor, but a finalize method is implicitly

called when garbage collector is about to reclaim the storage occupied by the object, e.g., to clean locks

Page 40: CS2403 Programming Languages Support for Object-Oriented Programming

40

Inheritance in Java

Single inheritance only, but interface provides some flavor of multiple inheritance

An interface like a class, but can include only method declarations and named constants, e.g., public interface Comparable <T> {

public int comparedTo (T b); } A class can inherit from another class and

“implement” an interface for multiple inheritance A method can have an interface as formal parameter,

that accepts any class that implements the interface a kind of polymorphism

Methods can be final (cannot be overridden)

Page 41: CS2403 Programming Languages Support for Object-Oriented Programming

41

Dynamic Binding in Java

In Java, all messages are dynamically bound to methods, unless the method is final (i.e., it cannot be overridden, and thus dynamic binding serves no purpose)

Static binding is also used if the method is static or private, both of which disallow overriding

Page 42: CS2403 Programming Languages Support for Object-Oriented Programming

42

Nested Classes in Java

Several varieties of nested classesAll are hidden from all classes in their

package, except for the nesting class Nonstatic classes nested directly are

called innerclassesAn innerclass can access members of its

nesting class, but not a static nested class Nested classes can be anonymous A local nested class is defined in a method

of its nesting class no access specifier is used

Page 43: CS2403 Programming Languages Support for Object-Oriented Programming

43

Evaluation of Java

Design decisions to support OOP are similar to C++

No support for procedural programming No parentless classes Dynamic binding is used as “normal” way

to bind method calls to method definitions Uses interfaces to provide a simple form

of support for multiple inheritance

Page 44: CS2403 Programming Languages Support for Object-Oriented Programming

44

Support for OOP in Ruby

General characteristicsEverything is an object and all computation is

through message passingClass definitions are executable, allowing

secondary definitions to add members to existing definitions

Method definitions are also executableAll variables are type-less references to objectsAccess control is different for data and methods

It is private for all data and cannot be changedMethods can be either public, private, or protectedMethod access is checked at runtime

Page 45: CS2403 Programming Languages Support for Object-Oriented Programming

45

Outline

Object-Oriented Programming (Sec. 12.2) Design Issues for OO Languages (Sec. 12.3) Support for OOP (Sec. 12.4 ~ 12.9)

SmalltalkC++JavaC#Ada 95Ruby

Implementation of OO Constructs (Sec. 12.10)

Page 46: CS2403 Programming Languages Support for Object-Oriented Programming

46

Implementing OO Constructs

Most OO constructs can be implemented easily by compilersAbstract data types scope rulesInheritance

Two interesting and challenging parts:Storage structures for instance variablesDynamic binding of messages to methods

Page 47: CS2403 Programming Languages Support for Object-Oriented Programming

47

Instance Data Storage

Class instance records (CIRs) store the state of an objectStatic (built at compile time and used as a

template for the creation of data of class instances)

Every class has its own CIR CRI for the subclass is a copy of that of the

parent class, with entries for the new instance variables added at the end

Because CIR is static, access to all instance variables is done by constant offsets from beginning of CIR

Page 48: CS2403 Programming Languages Support for Object-Oriented Programming

48

Dynamic Binding of Methods Calls

Methods in a class that are statically bound need not be involved in CIR; methods that are dynamically bound must have entries in the CIRCalls to dynamically bound methods can be

connected to the corresponding code thru a pointer in the CIR

Storage structure for the list of dynamically bound methods is called virtual method tables (vtable)

Method calls can be represented as offsets from the beginning of the vtable

Page 49: CS2403 Programming Languages Support for Object-Oriented Programming

49

Example of CIR in Java

public class A { public int a, b; public void draw() {...} public int area() {...}}

public class B extends A { public int c, d; public void draw() {...} public int sift() {...}}

Page 50: CS2403 Programming Languages Support for Object-Oriented Programming

50

Example CIR

Page 51: CS2403 Programming Languages Support for Object-Oriented Programming

51

Summary

OO programming involves three fundamental concepts: ADTs, inheritance, dynamic binding

Major design issues: exclusivity of objects, subclasses and subtypes,

type checking and polymorphism, single and multiple inheritance, dynamic binding, explicit and implicit de-allocation of objects, and nested classes

C++ has two distinct type system (hybrid) Java is not a hybrid language like C++; it

supports only OO programming