47
Object Oriented Programming Chapter 7 Programming Languages by Ravi Sethi

Object Oriented Programming Chapter 7 Programming Languages by Ravi Sethi

Embed Size (px)

Citation preview

Object Oriented ProgrammingChapter 7

Programming Languagesby Ravi Sethi

7.1 What Is An Object• Object-oriented program - Description or

simulation of application• Object-oriented programming is done by adopting

or extending an existing program.• Object - Entities in simulation

– An object can represent any entity in solution of problem

– An object interacts by sending messages– A computation is characterized in terms of

observable behavior of objects

7.2 Object Oriented Thinking• Vocabulary of object-oriented programming

– Object : Collection of data and operations

– Class: Description of a set of objects; objects with common properties[type of an object]

– Subclass: Subset of class, with additional properties; nested class

– Superclass: Main class that subclasses fall under

– Instance: Technical term for an object of class

– Method: Procedure body implementing an operation

– Message: Procedure call; request to execute method

• A class can have inheritance.– Single inheritance: Subclass has one superclass (Java)

– Multiple inheritance: Subclass has more than one superclass (C++)

• A message can carry parameters. An object will execute a method when gets a message[way responds].

• A class definition specifies the properties of an object. It includes methods it can execute and variables for the object.

Object Oriented Thinking (cont.)

• When storage is allocated for a variable of the class, we call that an instance.

7.3 Inheritance• Children of a class hierarchy inherit the methods

and variables of ancestor methods.• Object determines how it will implement a

message.• Information hiding facilitates two kinds of

changes:– Implementation change : If all interactions with an

object are through it’s interface, then algorithms and data structures are hidden behind the interface can be changed

• Inheritance change : If all interactions are through the interface to a superclass, then program can be extended by adding a subclass.

• Object-oriented programming often done by adopting or extending an existing program.

• Subclass is a derived class and superclass is a base class.

• A method in a subclass overrides an inherited method of the same name.

7.4 Object-Oriented Programming in C++

• C++ provides a transition path from C to object oriented programming.

• Declaring a class:– Constructor: Member function with same name

as class; called automatically when lifetime of an object of the class begins[used as an initialization method]

– Body of member function can appear within the declaration or separate

• Three keywords for controlling the visibility of members names.– Public: visible to outside code– Private: not visible to outside code– Keyword: visible through inheritance only

• Base and Derived Classes– Derived class: an extension of a base class

• Public Base Classes– Identified by the keyword public

– class <derived> : public <base> {

<member-declarations>

};– Members of a public base class retain their visibility in

the derived class

• Virtual Functions– Allow a derived class to supply the function body.

– Are taken from derived class where possible

• Initialization and Inheritance– Code for initialization belongs in the constructor for a

class

Object-Oriented Programming in C++(cont)

– Constructor of a base class is called before the derived class

– The destructor in derived class is called before the destructor in the base class

EXAMPLE

• A prime example of object orientation would be a program that draws diagrams.

• The object would be shapes.

• Can classify a shape based on its properties.

• Classification of shape objects– Figure 7.2 Page 257– Figure 7.3 Page 258

• Class Shape– Subclass Box– Subclass Line– Subclass Text– Subclass Ellipse

• Subclass Circle

• Methods of Shape would be– initialize, draw, offset, setwidth, setheight, and

setalign

• Variables of Object Shape– width, height, align

• Methods for each class Figure 7.6 Page 261• Since class box, ellipse, line, text are subclasses of

Shape; they will inherit the methods and variables from Shape

• What methods and variables would class circle inherit?

• Remember that Method Draw from Class box overrides Method Draw from Class Shape

Implementation of Shape(s)

• Implementation of Class Shape Figure 7.10 page 271

7.5 AN EXTENDED C++ EXAMPLE

This section illustrates inheritance in C++ by developing a program to find prime numbers.

A prime number is divisible only by itself and 1.

Primes:

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

A Prime Number Sieve

• Sieve method is used to compute primes.

• The underlying idea is that n is a prime if n is not a multiple of any prime p smaller than n.

• Objects used: counter(n) and filter(n)

A Base Class

class Item {

public :

Item *source;

Item(Item *src) { source = src; }

virtual int out() { return 0;}

};

Derived Classes

class Counter : public Item {

int value;

public :

int out() { return value++; }

Counter(int v) : Item(0) { value = v; }

};

Initialization of Derived and Base Classes

Counter(int v) : Item(0) { value = v; }

• Counter (int v) has an integer argument.

• : Item(0) passes the null pointer 0 as an argument to the constructor of the base class.

• { value = v; } is the body of the constructor in the derived class.

7.6 DERIVED CLASSES AND INFORMATION HIDING

• Inheritance is in terms of an is-a relation on objects.

• Hiding inherited members can interfere with a fundamental property, the ability of a derived object to appear wherever a base object is expected.

• Example : list and stack

Public Base Classes

• Syntax for a public base class :

class <derived> : public <base> {

<member-declarations>

};

• Members of a public base class retain their accessibility in the derived class.

Public Base Classes

• An object of a derived class has an is-a relation with objects of its public base class.

Private Base Classes

• Syntax for a private base class :

class <derived> : private <base> {

<member-declarations>

};

• A derived class simply shares the code of the private base class. Such code sharing is called implementation inheritance.

Private Base Classes

• All members derived by <derived> from <base> become private members of <derived>.

• Nonprivate inherited members can be made visible by writing their full names in the derived class.

Privacy Principle

• The private members of a class are accessible only to member functions of the class.

• Functions in a derived class cannot access the private members of its base class.

Privacy Principle

class List {

cell *rear;

public :

List();

int empty();

protected :

void add(int);

void push(int);

int get();

};

Privacy Principle

• class Queue : public List {

public :

Queue();

int get() { return List :: get(); }

void put(int x) { add(x) ;}

};

Privacy Principle

A complete listing of the members of class queue.

• Public Functions– Queue added constructor function– get added– put added– List :: empty inherited

Privacy Principle

• Protected functions– add inherited– push inherited– List :: get inherited

• Private Variables ( accessible to functions added by Queue )– none

Privacy Principle

• Private Variables ( accessible only to inherited functions )– rear inherited

7.7 OBJECTS IN SMALLTALK

Smalltalk is built on the concepts of objects and messages.

• Everything is an object.

• Data is private to an object.

• An object has a notion of self.

System classes

• Numbers, data structures, and input/output are provided by built-in system classes.

• Superclass and subclass vs. base class and derived class

Elements of a Class Definition

• Instance is a technical term for an object of a class

• Variables and methods– Class methods are used primarily to create

instances.– Class variables are used to share information

between instances.

A View of Class Stack in Smalltalk

class Stack superclass Object

instance variables

contents

class methods

new

^ super new initialize

A View of Class Stack in Smalltalk

instance methods

push: anElement

contents addLast: anElement

pop

^ contents removeLast

initialize

contents := OrderedCollection new

Instance Variables and Privacy

• An instance variable belongs to an instance. Its value can be changed only by operations belonging to the instance.

• How are the private variables initialized?

• Class variables are shared by all instances of a class.

• Global variables are shared by all instances of all classes.

Syntax of Messages

• Unary messages

contents size

• Keyword messages

aStack push: 54

• Binary messages

operators: +, -

Expression Evaluation

• Evaluation proceeds from left to right.

• Unary messages --- highest precedence

• Binary messages --- all with the same

precedence

• Keyword messages --- lowest precedence

Expression Evaluation

• Examples– contents size = 0

( contents size ) = 0– ( ( w*w ) + ( h*h ) ) sqrt

w*w + h*h = ( ( w*w ) + h ) * h )

Expression Evaluation

• The assignment symbol is <-- or := .

• A sequence of expressions is separated by dots or periods.w := width / 2 .

h := height / 2 .

r := ( ( w*w ) + ( h*h ) ) sqrt

Returning Values

• Return value operator : ^

• Return value operator has lower precedence than other messages.

• isEmpty

^ contents size = 0

^ ( ( contents size ) = 0 )

Conditionals and Blocks

• An expression sequence enclosed within square brackets, [ and ], is called a block.

• x > y if True: [ max := x ]

if False: [ max := y ]

• Blocks are objects.

7.8 SMALLTALK OBJECTS HAVE A SELF

The inheritance rules for Smalltalk

• Single inheritance means that each class has at most one superclass. The root of hierarchy is class object .

• A subclass inherits variables and methods from its superclass.

• A subclass can declare fresh variable names, different from the inherited variables.

• Methods in the subclass override inherited methods.

The rules for methods ensure that an object of a subclass can respond to all the messages that an object of a superclass can.

Messages to self

• Classes and objects can invoke one of their own methods by sending a message to the special name self.

• pop

Self isEmpty

if True: [ self error : ‘stack empty’ ]

if False: [ ^ contents removeLast ]

Messages to super

• When a subclass overrides an inherited method, the special name super allows the overridden method to be used.

• new

^ super new initialize