Vous êtes sur la page 1sur 19

www.jntuworld.

com

www.jwjobs.net
www.jntuworldupdates.org

Unit VII Data Abstraction and Object Orientation

UNIT VII
DATA ABSTRACTION AND OBJECT ORIENTATION

Abstraction Properties
Allow implementers to change an implementation without affecting the users of
the data structure.
Developmental independence (use specs even before an implementation is
written.
Complete separation of specifications from implementation.
Reusability.
Efficiency.
Conceptual clarity (precise client interfaces).
Information hiding (implementation details hidden from client).
User may think in terms of values (no surprise side effects).
Modular reasoning about correctness
1) Object Oriented Programming
Control or PROCESS abstraction is a very old idea (subroutines!), though
few languages provide it in a truly general form (Scheme comes close)
Data abstraction is somewhat newer, though its roots can be found in
Simula67
An Abstract Data Type is one that is defined in terms of the
operations that it supports (i.e., that can be performed upon it) rather
than in terms of its structure or implementation
Objects add inheritance and dynamic method binding
Simula 67 introduced these, but didn't have data hiding
The 3 key factors in OO programming
Encapsulation (data hiding)
Inheritance
Dynamic method binding

www.specworld.in

www.smartzworld.com
Page 1

www.jntuworld.com

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net
www.jntuworldupdates.org

Unit VII Data Abstraction and Object Orientation

The abstraction provided by modules and module types has at least three important
benefits.
1. It reduces conceptual load by minimizing the amount of detail that the
programmer must think about at one time.
2. It provides fault containment by preventing the programmer from using a
program component in inappropriate ways, and by limiting the portion of a
programs text in which a given component can be used, thereby limiting the
portion that must be considered when searching for the cause of a bug.
3. It provides a significant degree of independence among program components,
making it easier to assign their construction to separate individuals, to modify their
internal implementations without changing external code that uses them, or to
install them in a library where they can be used by other programs.
By deriving new classes from old ones, the programmer can create
arbitrarily deep class hierarchies, with additional functionality at every level
of the tree.
When created with new, an object is allocated in the heap; when created via
elaboration of a declaration it is allocated statically or on the stack, depending on
lifetimecreation causes the invocation of a programmer-specified initialization
routine, known as a constructor. In C++ and its descendants, Java and C#, the
name of the constructor is the same as that of the class itself. C++ also allows the
programmer to specify a destructor method that will be invoked automatically
when an object is destroyed, either by explicit programmer action or by return
from the subroutine in which it was declared. The destructors name is also the
same as that of the class, but with a leading tilde (~).
Public and Private Members
The Access specifier for the OOPs are : Private, Public and Protected.
In Java,
 Private:
The most restrictive access level is private.
A private member is accessible only to the class in which it is defined.
Inheritance does not apply on the private members. They are Just like
secrets.
Use private keyword to create private members.
www.specworld.in
2
www.smartzworld.com
 Protected:
Page 2

www.jntuworld.com

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net
www.jntuworldupdates.org

Unit VII Data Abstraction and Object Orientation

Allows the class itself, subclasses, and all classes in the same package
to access the members.
Use the protected access level when it's appropriate for a class's
subclasses to have access to the member, but not unrelated classes.
Protected members are like family secrets.
To declare a protected member, use the keyword protected
Public:
The easiest access specifier is public.
Any class, in any package, has access to a class's public members.
Declare public members only if such access cannot produce
undesirable results if an outsider uses them.
There are no personal or family secrets here; this is for stuff you don't
mind anybody else knowing.
To declare a public member, use the keyword public.
In C++
Declared in the body of the class
May be public or private
Exist throughout the life of the object.
Stored in class object.
Each object has its own copy.
May be objects of any type
Access-specifier private
Makes any member accessible only to member functions of the class.
May be applied to data members and member functions
Default access for class members
Encourages information hiding
As a rule of thumb, data members should be declared private
Member functions should be declared public.
Except member functions that are accessed only by other member
functions of the class.
Often useful to have get and set functions
To access private members in controlled ways

www.specworld.in

www.smartzworld.com
Page 3

www.jntuworld.com

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net
www.jntuworldupdates.org

Unit VII Data Abstraction and Object Orientation

Tiny Subroutines
Object-oriented programs tend to make many more subroutine calls than do
ordinary imperative programs, and the subroutines tend to be shorter. Many
programmers in fact consider it bad style to declare public fields, because they give
users of an abstraction direct access to the internal representation.
Property and indexer methods in C#
C# provides a property mechanism specifically designed to facilitate the declaration of methods to get and set values. Using this mechanism, our val field
could be written as follows.
class list_node {
...
int val;
public int Val {
get { // presence of get and optional set
return val; // methods means that Val is a property
}
set {
val = value; // value is a keyword: argument to set
}
}
...
}
Users of the list_node class can now access the (private) val field through the
(public) Val property as if it were a field:
list_node n;
...
int a = n.Val; // implicit call to get method
n.Val = 3; // implicit call to set method
A indexer mechanism can make objects of arbitrary classes look like arrays,with
conventional subscript syntax in both l-value and r-value contexts. In C++,
operator overloading and references can be used to provide the equivalent of
indexers, but not of properties
Derived Classes
New classes created from existing ones is called inheritance..
 Existing class is called Base class/parent class / Sub Class.
 New class is called Derived/Child/Sub Class.

www.specworld.in

www.smartzworld.com
Page 4

www.jntuworld.com

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net
www.jntuworldupdates.org

Unit VII Data Abstraction and Object Orientation

In C++,
class Shape
{
public:
int GetColor ( ) ;
protected:
// so derived classes can access it
int color;
};
class Two_D : public Shape
{
// put members specific to 2D shapes here
};
class Three_D : public Shape
{
// put members specific to 3D shapes here
};
Shape is the base class and two-D & Three-D are derived classes and can
access the method getColor().
In java,
public class derived-class-name extends base-class-name {
// derived class methods extend and possibly override
// those of the base class
}
By deriving new classes from old ones, the programmer can create arbitrarily
deep class hierarchies, with additional functionality at every level of the tree.

General Purpose Base Classes


we can create a general purpose element base class that contains only the
fields and methods needed to implement list operations:
Class that contains one or more abstract methods
Java: called an interface (which has only abstract methods)

www.specworld.in

www.smartzworld.com
Page 5

www.jntuworld.com

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net
www.jntuworldupdates.org

Unit VII Data Abstraction and Object Orientation

Generally not possible to declare object of an abstract class b/c it would be


missing at least one member
But you can do so in C++
Serves as a base for concrete classes.
Concrete class must provide a definition for every abstract method it
inherits

class gp_list_node {
gp_list_node* prev;
gp_list_node* next;
gp_list_node* head_node;
public:
gp_list_node(); // assume method bodies given separately
gp_list_node* predecessor();
gp_list_node* successor();
bool singleton();
void insert_before(gp_list_node* new_node);
void remove();
~gp_list_node();
};
Now we can use this general purpose class to derive lists and queues with
specific
types of fields:
class int_list_node : public gp_list_node {
public:
int val; // the actual data in a node
int_list_node() {
val = 0;
}
int_list_node(int v) {
val = v;
}
};
In Java the general class is represented in the form of Abstract Base Classes
An abstract class is a class that leaves one or more method implementations
unspecified by declaring one or more methods abstract. An abstract method has no
body (i.e., no implementation). A subclass is required to override the abstract

www.specworld.in

www.smartzworld.com
Page 6

www.jntuworld.com

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net
www.jntuworldupdates.org

Unit VII Data Abstraction and Object Orientation

method and provide an implementation. Hence, an abstract class is incomplete and


cannot be instantiated, but can be used as a base class.
abstract public class abstract-base-class-name {
// abstract class has at least one abstract method
public abstract return-type abstract-method-name ( formal-params );
... // other abstract methods, object methods, class methods
}
public class derived-class-name extends abstract-base-class-name {
public return-type abstract-method-name (formal-params) { stmt-list; }
... // other method implementations
}
It would be an error to try to instantiate an object of an abstract type:
abstract-class-name obj = new abstract-class-name(); // ERROR!
That is, operator new is invalid when applied to an abstract class

Overloaded Constructor
A Class can have more than one constructor in a class, as long as each
has a different list of arguments.
C++,
class rectangle {
private:
float height;
float width;
int xpos;
int ypos;
public:
rectangle(float, float); // constructor
rectangle();
// another constructor
void draw();
// draw member function
void posn(int, int); // position member function
void move(int, int); // move member function
rectangle::rectangle()
{
height = 10;
width = 10;
www.specworld.in
7
xpos = 0;

www.smartzworld.com
Page 7

www.jntuworld.com

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net
www.jntuworldupdates.org

Unit VII Data Abstraction and Object Orientation

ypos = 0;
}
void main()
{
rectangle rc1(3.0, 2.0);
rectangle rc2();
rc1.draw();
rc2.draw();

Modifying Base Class Methods


In addition to defining new fields and methods, a derived class can hide or redefine
members of base class(es). To redefine a method of a base class, a derived class
simply declares a new version.
 Overriding a method in a subclass means re-writing or modifying its code so
that it acts differently from what it used to.
 Method overriding is related to a very important feature of OOP known as
polymorphism
 Example: Overriding methods init() or paint() in applets.
In C++,
gp_list_node::remove(); // C++
super.remove(); // Java
base.remove(); // C#
super remove. // Smalltalk
[super remove] // Objective-C _
In Eiffel, onemust explicitly renamemethods inherited froma base class, in order
to make them accessible:
class int_list_node
inherit
gp_list_node
rename
remove as old_remove
... -- other renames
end

www.specworld.in

www.smartzworld.com
Page 8

www.jntuworld.com

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net
www.jntuworldupdates.org

Unit VII Data Abstraction and Object Orientation

Within methods of int_list_node, the remove method of gp_list_node can be


invoked as old_remove. C++ and Eiffel cannot use the keyword super, because
it would be ambiguous in the presence of multiple inheritance.
Containers/Collections
In object-oriented programming, an abstraction that holds a collection of objects
of some given class is often called a container. There are several different ways to
build containers.
2) Encapsulation and Inheritance
Encapsulation mechanisms enable the programmer to group data and
the subroutines
that operate on them together in one place, and to hide irrelevant
details
from the users of an abstraction.
 Inheritance is a form of software reusability where
New classes created from existing ones
Subclasses absorb super-classes attributes and behaviors, and
add in their own.
The Object class defines and implements behavior that every class
in the Java system needs.
Modules
Scope rules for data hiding were one of the principal innovations of Clu, Modula,
Euclid, and other module-based languages of the 1970s. In Clu and Euclid, the
declaration and definition (header and body) of a module always appear together.
The header clearly states which of the modules names are to be exported. In Clu, a
module (called a cluster) implements a single abstract type. Assignment and
equality testing are permitted for that type, but because Clu uses a reference model
for variables, these operations copy or compare references to objects, not the
objects themselves.
If a module M exports a type T, the rest of the program can only pass T to
subroutines exported from M.
T is said to be an opaque type.
var Database : module
exports (tuple with (:=, name))

type tuple = record


www.specworld.in
9
www.smartzworld.com
var name : packed array 1..80 of char
Page 9

www.jntuworld.com

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net
www.jntuworldupdates.org

Unit VII Data Abstraction and Object Orientation

end tuple
The this Parameter
This replication would be highly wasteful, however, as the copies would vary only
in the details of address computations. A better technique is to create a single
instance of each module subroutine, and to pass that instance, at run time, the
address of the storage of the appropriate module instance.

3) Initialization and Finalization


the lifetime of an object to be the interval during which it occupies space
and can hold data
Most object-oriented languages provide some sort of special
mechanism to initialize an object automatically at the beginning of
its lifetime
When written in the form of a subroutine, this mechanism is
known as a constructor
A constructor does not allocate space
A few languages provide a similar destructor mechanism to finalize
an object automatically at the end of its lifetime
1. choosing a constructor: An object-oriented language may permit a class to
have
zero, one, or many distinct constructors. In the latter case, different constructors
may have different names, or it may be necessary to distinguish among
them by number and types of arguments.
2. references and values: If variables are references, then every object must be
created explicitly, and it is easy to ensure that an appropriate constructor is
called.If variables are values, then object creation can happen implicitly as a
result of elaboration. In this latter case, the language must either permit objects
to begin their lifetime uninitialized, or itmust provide a way to choose an
appropriate constructor for every elaborated object.
3. execution order: When an object of a derived class is created in C++, the
compiler guarantees that the constructors for any base classes will be executed,
outermost first, before the constructor for the derived class. Moreover, if a class
has members that are themselves objects of some class, then the constructors for
the members will be called before the constructor for the object in which they
are contained. These rules are a source of considerable syntactic and semantic

www.specworld.in

10

www.smartzworld.com
Page 10

www.jntuworld.com

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net
www.jntuworldupdates.org

Unit VII Data Abstraction and Object Orientation

complexity: when combined with multiple constructors, elaborated objects, and


multiple inheritance they can sometimes induce a complicate sequence of
nested constructor invocations, with overload resolution, before control even
enters a given scope. Other languages have simpler rules.
4. garbage collection: Most object-oriented languages provide some sort of
constructor mechanism. Destructors are comparatively rare. Their
principal purpose is to facilitate manual storage reclamation in languages
like C++. If the language implementation collects garbage automatically,
then the need for destructors is greatly reduced.
Choosing a Constructor
Smalltalk, Eiffel, C++, Java, and C# all allow the programmer to specify more than
one constructor for a given class. In C++, Java, and C#, the constructors behave
like overloaded subroutines: they must be distinguished by their numbers and types
of arguments. In Smalltalk and Eiffel, different constructors can have different
names; code that creates an object must name a constructor explicitly. The !!
operator is Eiffels equivalent of new.
Smalltalk resembles Eiffel in the use of multiple named constructors, but it
distinguishes more sharply between operations that pertain to an individual object
and operations that pertain to a class of objects. Smalltalk also adopts an
anthropomorphic programming model in which every operation is seen as being
executed by some specific object in response to a request (a message) from some
other object Modula-3 and Oberon provide no constructors at all: the programmer
must initialize everything explicitly. Ada 95 supports constructors and destructors
(called Initialize and Finalize routines) only for objects of types derived from the
standard library type Controlled.
References and Values
C++ vs. Java
Java uses reference, C++ you can specify
Reference
Every object is created explicitly so it is easy to make sure the correct
constructor is called.
More elegant, but requires allocation from heap and extra indirections
on every access of the object.
Value
control initialization
www.specworld.in More efficient but harder to 11
www.smartzworld.com
Page 11

www.jntuworld.com

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net
www.jntuworldupdates.org

Unit VII Data Abstraction and Object Orientation

Several object-oriented languages, including Simula, Smalltalk, Python, Ruby,and


Java, use a programming model in which variables refer to objects. Other
languages, including C++, Modula-3, Ada 95, and Oberon, allow a variable to have
a value that is an object. Eiffel uses a reference model by default, but allows the
programmer to specify that certain classes should be expanded, inwhich case
variables of those classes will use a value model. In a similar vein, C# uses struct
to define types whose variables are values, and class to define typeswhose
variables are references.
Execution Order
If class B is derived from class A, A constructor is called before B
constructor
To get arguments to the A constructor, you must use an intializer list
class foo : bar {
...
}
foo::foo (foo_params) : bar(bar_params) {

The part after the colon is a call to bars constructor


the objects class (call it B) is derived from some other class (call itA), C++ insists
on calling an A constructor before calling a B constructor, so the derived class is
guaranteed never to see its inherited fields in an inconsistent state.When the
programmer creates an object of class B (either via declaration or with a call to
new), the creation operation specifies arguments for a B constructor. constructor
when the surrounding object is created. Smalltalk, Eiffel, and CLOS are all more
lax than C++ regarding the initialization of base classes. The compiler or
interpreter arranges to call the constructor (creator, initializer) for each newly
created object automatically, but it does not arrange to call constructors for base
classes automatically; all it does is initialize base class data members to default (0
or null) values
Garbage Collection
When an object is destroyed, the destructor is called for the derived class
first, then the destructors of the base classes are called.
Reverse order of derivation
www.specworld.in
12
Destructors purpose is to return allocated
space back to the heap www.smartzworld.com
Page 12

www.jntuworld.com

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net
www.jntuworldupdates.org

Unit VII Data Abstraction and Object Orientation

Many languages provide automatic garbage collection


Java, Smalltalk, Eiffel, etc.
In C++,
Destructor: a function used to clean up an object of a class prior to deleting
that object
Class name preceeded by '~'
No parameters, no result
Called automatically
When function exits scope of automatic class object
By delete operator
In Java, you can override the finalize() method
This allows code to be executed when the object is about to be deleted
But you shouldnt extend the objects lifetime by doing this
As the finalize() method is only called once per object
4) Dynamic Method Binding
One of the principal consequences of inheritance/type extension is
that a derived class D has all the membersdata and subroutinesof
its base class C.
Virtual functions in C++ are an example of dynamic method
binding
you don't know at compile time what type the object referred
to by a variable will be at run time
Simula
also
had
virtual
functions
(all
of
which are abstract)
In Smalltalk, Eiffel, Modula-3, and Java all member functions are
virtual
Static method binding uses the type of the reference:
s.print_mailing_label();
p.print_mailing_label();
Dynamic method binding uses the class of the object that is referred/pointed
to:
www.specworld.in
13
www.smartzworld.com
x->print_mailing_label();
Page 13

www.jntuworld.com

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net
www.jntuworldupdates.org

Unit VII Data Abstraction and Object Orientation

y->print_mailing_label();
Virtual and Nonvirtual Methods

Bodyless virtual methods


In C++: called pure virtual method, created by following a procedure
declaration with an assignment to zero.
class person {

public:
virtual void print_mailing_label() = 0;

Abstract Classes
Class that contains one or more abstract methods
Java: called an interface (which has only abstract methods)
Generally not possible to declare object of an abstract class b/c it would be
missing at least one member
But you can do so in C++
Serves as a base for concrete classes.
Concrete class must provide a definition for every abstract method it
inherits
Application to dynamic method binding: allows code that calls methods of
objects of a base class, assuming that the concrete methods will be invoked
at run time
Member Lookup
In dynamic binding each object is represented with a record whose first field
contains the address of a virtual method table (vtable) for that objects class
Our objects are being more complicated for the compiler to manage
Virtual method tables
Reference counts
Etc

www.specworld.in

14

www.smartzworld.com
Page 14

www.jntuworld.com

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net
www.jntuworldupdates.org

Unit VII Data Abstraction and Object Orientation

Polymorphism
A derived class (D) has all the members of its base class (C)
Class D can be used anytime class C is expected.
If class D does not hide any 15publicly visible members of Cwww.smartzworld.com
then D is a
www.specworld.in
subtype of C.
www.jntuworld.com

Page 15

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net
www.jntuworldupdates.org

Unit VII Data Abstraction and Object Orientation

If class D is used in place of class C, this is a form of polymorphism.


class person {
class student : public person {
class professor : public person {
student s;
professor p;

person *x = &s;
person *y = &p;

5) Multiple Inheritance
It means derived class to inherit features from more than one base class. For
Example College and Department are two base classes then the students is a
class which can use features of both the College and Department class.
College

Department

Students
In C++, The multiple inheritance is implemented as
class

Students

public

College,

public

Department

...
}
In Java the multiple Inheritance is not implemented directly but via
interface as,
interface College
{ .}
interface Department
{}
Class students implements College, Department
{

}
www.specworld.in

16

www.smartzworld.com

Here you get all the members of College and all the members of Department

Page 16

www.jntuworld.com

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net
www.jntuworldupdates.org

Unit VII Data Abstraction and Object Orientation

If there's anything that's in both (same name and argument types),


then calls to the member are ambiguous; the compiler disallows them

Multiple inheritance with a common grandparent is known as


repeated inheritance.
Repeated inheritance with separate copies of the grandparent is knownas replicated
inheritance; repeated inheritance with a single copy of the grandparent is known as
shared inheritance. Shared inheritance is the default in Eiffel.Replicated
inheritance is the default in C++. Both languages allow the programmer to obtain
the other option when desired.
1) Object-Oriented Programming Revisited

Anthropomorphism is central to the OO paradigm - you think in terms of


real-world objects that interact to get things done
Many OO languages are strictly sequential, but the model adapts well to
parallelism as well
Strict interpretation of the term
uniform data abstraction - everything is an object
inheritance
-- dynamic method binding
Lots of conflicting uses of the term out there object-oriented style available
in many languages
data abstraction crucial
inheritance required by most users of the term O-O
centrality of dynamic method binding a matter of dispute
SMALLTALK is the canonical object-oriented language
It has all three of the characteristics listed above
It's based on the thesis work of Alan Kay at Utah in the late 1960s
It went through 5 generations at Xerox PARC, where Kay worked
after graduating
Smalltalk-80 is the current standard
Modula-3
single inheritance
all methods virtual
www.specworld.in
17
www.smartzworld.com
no constructors or destructors
Page 17

www.jntuworld.com

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net
www.jntuworldupdates.org

Unit VII Data Abstraction and Object Orientation

Ada 95
tagged types
single inheritance
no constructors or destructors
class-wide parameters:
methods static by default
can define a parameter or pointer that grabs the object-specific
version of all methods
base class doesn't have to decide what will be virtual
notion of child packages as an alternative to friends
Java
interfaces, mix-in inheritance
alternative to multiple inheritance
basically you inherit from one real parent and one or more
interfaces, each of which contains only virtual functions and no
data
this avoids the contiguity issues in multiple inheritance above,
allowing a very simple implementation
all methods virtual
Is C++ object-oriented?
Uses all the right buzzwords
Has (multiple) inheritance and generics (templates)
Allows creation of user-defined classes that look just like built-in ones
Has all the low-level C stuff to escape the paradigm
Has friends
Has static type checking
In the same category of questions:
Is Prolog a logic language?
Is Common Lisp functional?
However, to be more precise:
Smalltalk is really pretty purely object-oriented
Prolog is primarily logic-based
Common Lisp is largely functional
C++ can be used in an object-oriented
style
www.specworld.in
18

www.smartzworld.com
Page 18

www.jntuworld.com

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net
www.jntuworldupdates.org

Unit VII Data Abstraction and Object Orientation

RESOLVE

Language prototype for the future


Designed with verification in mind
Includes mathematical specifications
Reusable components
Information hiding
Strong, static typing
Parameter passing by swap

www.specworld.in

19

www.smartzworld.com
Page 19

www.jntuworld.com

www.jntuworld.com

Vous aimerez peut-être aussi