0% found this document useful (0 votes)
23 views51 pages

L10 Abstract

The document discusses the principles and features of Object-Oriented Programming (OOP), emphasizing the importance of abstract data types (ADTs), inheritance, and polymorphism. It outlines design issues for OOP languages, including type checking, dynamic and static binding, and the implications of single versus multiple inheritance. Additionally, it provides examples of inheritance in C++ and highlights the complexities and advantages of various inheritance strategies.

Uploaded by

jefferjam716
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views51 pages

L10 Abstract

The document discusses the principles and features of Object-Oriented Programming (OOP), emphasizing the importance of abstract data types (ADTs), inheritance, and polymorphism. It outlines design issues for OOP languages, including type checking, dynamic and static binding, and the implications of single versus multiple inheritance. Additionally, it provides examples of inheritance in C++ and highlights the complexities and advantages of various inheritance strategies.

Uploaded by

jefferjam716
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 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)
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
2
What Are Needed?
 Given a collection of related ADTs, need to
factor out their commonality and put it in
a new type  abstraction
 The collection of ADTs then inherit from the
new type and add their own
class Shape { class Circle: public Shape {
private: private:
int x; int y; int radius;
public: public:
Shape(int a, int b); Circle(int x1, y2, r1);
... ...
virtual void draw(); void draw();
}; };
3
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
time
Shape *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) 4
Object-Oriented Programming
 Anobject-oriented language must provide
supports for three key features:
 Abstract data types
 Inheritance: the central theme in OOP and
languages that support it
 Polymorphism and dynamic binding
 Whatdoes it mean in a pure OO program,
where x, y, and 3 are objects?
y = x + 3;

5
Outline
 Object-Oriented Programming (Sec. 12.2)
 Design Issues for OO Languages (Sec. 12.3)
 Support for OOP (Sec. 12.4 ~ 12.9)
 Smalltalk
 C++
 Java
 C#
 Ada 95
 Ruby
 Implementation of OO Constructs (Sec.
12.10)
6
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()
7
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
8
Inheritance
 Allows new classes defined in terms of
existing ones, i.e., by inheriting common
parts
 Can be complicated by access controls to
encapsulated entities
 A class can hide entities from its subclasses
(private)
 A class can hide entities from its clients
 A 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 one
 The method in the parent is overridden
9
Inheritance (cont.)
 There are two kinds of variables in a class:
 Class variables - one/class
 Instance variables - one/object, object state
 There are two kinds of methods in a class:
 Class methods – accept messages to the class
 Instance methods – accept messages to
objects
 Singlevs. multiple inheritance
 One disadvantage of inheritance for reuse:
 Creates interdependencies among classes that
complicate maintenance
10
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 descendants
Shape *shape_list[3]; // array of shapes
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();
}
11
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

12
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 method
 An Shape
abstract
class { class cannot be Circle:
class instantiated
public Shape {
private: private:
int x; int y; int radius;
public: public:
... ...
virtual void draw(); void draw() {...};
}; };

13
Outline
 Object-Oriented Programming (Sec. 12.2)
 Design Issues for OO Languages (Sec. 12.3)
 Support for OOP (Sec. 12.4 ~ 12.9)
 Smalltalk
 C++
 Java
 C#
 Ada 95
 Ruby
 Implementation of OO Constructs (Sec.
12.10)
14
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

15
The Exclusivity of Objects
 Option 1: Everything is an object
 Advantage: elegance and purity
 Disadvantage: slow operations on simple objects
 Option 2: Add objects to existing typing
system
 Advantage: fast operations on simple objects
 Disadvantage: confusing typing (2 kinds of entities)
 Option 3: Imperative-style typing system for
primitives and everything else objects
 Advantage: fast operations on simple objects and a
relatively small typing system
 Disadvantage: still confusing by two type systems
16
Are Subclasses Subtypes?
 Doesan “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 object
subtype 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

17
Type Checking and
Polymorphism
 Polymorphism may require dynamic type
checking of parameters and the return
value
 Dynamic type checking is costly and delays
error detection
 Ifoverriding methods are restricted to
having the same parameter types and
return type, the checking can be static

18
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
19
Object Allocation and
Deallocation
 From where are objects allocated?
 If behave like ADTs, can be allocated from
anywhere
 Allocated from the run-time stack
 Explicitly created on the heap (via new)
 If they are all heap-dynamic, references can be
uniform thru a pointer or reference variable
 Simplifies 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?
20
Dynamic and Static Binding
 Should
all binding of messages to
methods be dynamic?
 If none are, you lose the advantages of
dynamic binding
 If all are, it is inefficient
 Alternative: allow the user to specify

21
Nested Classes
 Ifa new class is needed by only one class,
no reason to define it to be seen by other
classes
 Can 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

22
Initialization of Objects
 Areobjects initialized to values when they
are created?
 Implicit or explicit initialization

 Howare parent class members initialized


when a subclass object is created?

23
Outline
 Object-Oriented Programming (Sec. 12.2)
 Design Issues for OO Languages (Sec. 12.3)
 Support for OOP (Sec. 12.4 ~ 12.9)
 Smalltalk
 C++
 Java
 C#
 Ada 95
 Ruby
 Implementation of OO Constructs (Sec.
12.10)
24
Inheritance in C++
 Inheritance
 A class need not be the subclass of any class
 Access 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

25
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 subclasses
 Private 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

26
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 public
class subclass_2 : private base_class {…};
// b, y, c, z private; no access by derived
27
Inheritance Example 2 in C++
class base{
int x; Where are
public: the errors?
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"; } };
(http://www.umsl.edu/~subramaniana/private_inherit.html)
28
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)

29
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 derivation
 A 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
30
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(); }
31
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() ...
};
32
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 desirable
 Public 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

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

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

35
Dynamic Binding in C++
A method can be defined to be virtual,
and can be called through polymorphic
variables and dynamically bound to
messages
 A pure virtual function has no definition at all
A class that has at least one pure virtual
function
class Shape {is an abstract class
class Circle: public Shape {
public: public:
... ...
virtual void draw()=0; void draw() {...};
}; };

36
Dynamic Binding in C++
(cont.)
square* sq = new square;
rectangle* rect = new rectangle;
shape* shape_ptr;
shape_ptr = sq;
shape_ptr->draw(); // dynamically bound
rect = sq;
rect->draw(); // statically bound
square sq1; // sq1 on stack
rectangle rect1;
rect1 = sq1; // copy data member values
rect1.draw();
37
Support for OOP in C++
 Evaluation
 C++ provides extensive access controls
(unlike Smalltalk)
 C++ provides multiple inheritance
 Programmer must decide at design time which
methods will be statically or dynamically
bound
 Static binding is faster!
 Smalltalk type checking is dynamic (flexible,
but somewhat unsafe and is ~10 times slower
due to interpretation and dynamic binding

38
Support for OOP in Java
 Focuson the differences from C++
 General characteristics
 All data are objects except the primitive types
 All primitive types have wrapper classes to store data
value, e.g., myArray.add(new Integer(10));
 All classes are descendant of the root class, Object
 All objects are heap-dynamic, are referenced through
reference variables, and most are allocated with new
 No 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

39
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)

40
Dynamic Binding in Java
 InJava, 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

41
Nested Classes in Java
 Several varieties of nested classes
 All are hidden from all classes in their
package, except for the nesting class
 Nonstatic classes nested directly are
called innerclasses
 An 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

42
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

43
Support for OOP in Ruby
 General characteristics
 Everything is an object and all computation is
through message passing
 Class definitions are executable, allowing
secondary definitions to add members to existing
definitions
 Method definitions are also executable
 All variables are type-less references to objects
 Access control is different for data and methods
 It is private for all data and cannot be changed
 Methods can be either public, private, or protected
 Method access is checked at runtime

44
Outline
 Object-Oriented Programming (Sec. 12.2)
 Design Issues for OO Languages (Sec. 12.3)
 Support for OOP (Sec. 12.4 ~ 12.9)
 Smalltalk
 C++
 Java
 C#
 Ada 95
 Ruby
 Implementation of OO Constructs (Sec.
12.10)
45
Implementing OO Constructs
 Most OO constructs can be implemented
easily by compilers
 Abstract data types  scope rules
 Inheritance
 Two interesting and challenging parts:
 Storage structures for instance variables
 Dynamic binding of messages to methods

46
Instance Data Storage
 Classinstance records (CIRs) store the state
of an object
 Static (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
47
Dynamic Binding of Methods
Calls
 Methodsin a class that are statically
bound need not be involved in CIR;
methods that are dynamically bound must
have entries in the CIR
 Calls 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
48
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() {...}
}
49
Example CIR

50
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
51

You might also like