Unit 3
Unit 3
PROGRAMMING PARADIGM
1
Low level
• Initially, computers were hard-wired or soft-wired and then later
programmed using binary code that represented control sequences fed to
the computer CPU.
• This was difficult and error-prone. Programs written in binary are said to
be written in machine code, which is a very low-level programming
paradigm. Hard-wired, soft-wired, and binary programming are considered
first generation languages.
2
Low level
• To make programming easier, assembly languages were developed.
4
PROCEDURAL PROGRAMMING
PARADIGM
5
Procedural programming
• Often thought as a synonym for imperative programming.
• Specifying the steps the program must take to reach the desired state.
• Based upon the concept of the procedure call.
• Procedures, also known as routines, subroutines, methods, or functions that
contain a series of computational steps to be carried out.
• Any given procedure might be called at any point during a program's execution,
including by other procedures or itself.
6
Procedural programming
• Possible benefits:
– Often a better choice than simple sequential or unstructured programming in many situations which
involve moderate complexity or require significant ease of maintainability.
– The ability to re-use the same code at different places in the program without copying it.
– An easier way to keep track of program flow than a collection of "GOTO" or "JUMP" statements
(which can turn a large, complicated program into spaghetti code).
– The ability to be strongly modular or structured.
• Modularity was one of the earliest abstraction features identified as desirable for a
programming language.
7
Procedural programming
• Scoping is another abstraction technique that helps to keep procedures strongly
modular.
• It prevents a procedure from accessing the variables of other procedures (and vice-
versa), including previous instances of itself such as in recursion.
• Procedures are convenient for making pieces of code written by different people or
different groups, including through programming libraries.
– specify a simple interface
– self-contained information and algorithmics
– reusable piece of code
8
Procedural programming
• The focus of procedural programming is to break down a programming task into a
collection of variables, data structures, and subroutines, whereas in object-
oriented programming it is to break down a programming task into objects with
each "object" encapsulating its own data and methods (subroutines).
9
Procedural programming
• The earliest imperative languages were the machine languages of the original computers. In
these languages, instructions were very simple, which made hardware implementation
easier, but hindered the creation of complex programs.
• FORTRAN (1954) was the first major programming language to remove through abstraction
the obstacles presented by machine code in the creation of complex programs.
• FORTRAN was a compiled language that allowed named variables, complex expressions,
subprograms, and many other features now common in imperative languages.
• In the late 1950s and 1960s, ALGOL was developed in order to allow mathematical algorithms
to be more easily expressed.
• In the 1970s, Pascal was developed by Niklaus Wirth, and C was created by Dennis Ritchie.
• For the needs of the United States Department of Defense, Jean Ichbiah and a team at
Honeywell began designing Ada in 1978.
10
OBJECT-ORIENTED PROGRAMMING
PARADIGM
11
Object-oriented programming
• Object-oriented programming (OOP) is a programming paradigm that uses
"objects" – data structures encapsulating data fields and procedures
together with their interactions – to design applications and computer
programs.
• Though it was invented with the creation of the Simula language in 1965,
and further developed in Smalltalk in the 1970s, it was not commonly used
in mainstream software application development until the early 1990s.
12
OOP concepts: class
• A class defines the abstract characteristics of a thing (object), including that thing's
characteristics (its attributes, fields or properties) and the thing's behaviors (the
operations it can do, or methods, operations or functionalities).
• One might say that a class is a blueprint or factory that describes the nature of
something.
• Collectively, the properties and methods defined by a class are called its members.
13
OOP concepts: object
– An object is an individual of a class created at run-time trough object instantiation
from a class.
– The set of values of the attributes of a particular object forms its state. The object
consists of the state and the behavior that's defined in the object's class.
– The object is instantiated by implicitly calling its constructor, which is one of its
member functions responsible for the creation of instances of that class.
14
OOP concepts: attributes
• An attribute, also called data member or member variable, is the data encapsulated within a class
or object.
• In the case of a regular field (also called instance variable), for each instance of the object there is
an instance variable.
• A static field (also called class variable) is one variable, which is shared by all instances.
• Attributes are an object’s variables that, upon being given values at instantiation (using a
constructor) and further execution, will represent the state of the object.
• A class is in fact a data structure that may contain different fields, which is defined to contain the
procedures that act upon it. As such, it represents an abstract data type.
• In pure object-oriented programming, the attributes of an object are local and cannot be seen from
the outside. In many object-oriented programming languages, however, the attributes may be
accessible, though it is generally considered bad design to make data members of a class as
externally visible.
15
OOP concepts: method
• A method is a subroutine that is exclusively associated either with a class (in which
case it is called a class method or a static method) or with an object (in which case
it is an instance method).
16
OOP concepts: method
• instance methods are associated with an object
• class or static methods are associated with a class.
• The object-oriented programming paradigm intentionally favors the use of
methods for each and every means of access and change to the underlying data:
– Constructors: Creation and initialization of the state of an object. Constructors are called
automatically by the run-time system whenever an object declaration is encountered in the code.
– Retrieval and modification of state: accessor methods are used to access the value of a particular
attribute of an object. Mutator methods are used to explicitly change the value of a particular
attribute of an object. Since an object’s state should be as hidden as possible, accessors and mutators
are made available or not depending on the information hiding involved and defined at the class level
– Service-providing: A class exposes some “service-providing” methods to the exterior, who are
allowing other objects to use the object’s functionalities. A class may also define private methods
who are only visible from the internal perspective of the object.
– Destructor: When an object goes out of scope, or is explicitly destroyed, its destructor is called by
the run-time system. This method explicitly frees the memory and resources used during its
execution.
17
OOP concepts: method
– The difference between procedures in general and an object's method is that the
method, being associated with a particular object, may access or modify the data
private to that object in a way consistent with the intended behavior of the object.
– So rather than thinking "a procedure is just a sequence of commands", a
programmer using an object-oriented language will consider a method to be "an
object's way of providing a service“. A method call is thus considered to be a
request to an object to perform some task.
– Method calls are often modeled as a means of passing a message to an object.
Rather than directly performing an operation on an object, a message is sent to the
object telling it what it should do. The object either complies or raises an exception
describing why it cannot do so.
– Smalltalk used a real “message passing” scheme, whereas most object-oriented
languages use a standard “function call” scheme for message passing.
– The message passing scheme allows for asynchronous function calls and thus
concurrency.
18
OOP concepts: inheritance
• Inheritance is a way to compartmentalize and reuse code by creating collections of
attributes and behaviors (classes) which can be based on previously created
classes.
• The new classes, known as subclasses (or derived classes), inherit attributes and
behavior of the pre-existing classes, which are referred to as superclasses (or
ancestor classes). The inheritance relationships of classes gives rise to a hierarchy.
• Multiple inheritance can be defined whereas a class can inherit from more than
one superclass. This leads to a much more complicated definition and
implementation, as a single class can then inherit from two classes that have
members bearing the same names, but yet have different meanings.
• Abstract inheritance can be defined whereas abstract classes can declare member
functions that have no definitions and are expected to be defined in all of its
subclasses.
19
OOP concepts: abstraction
• Abstraction is simplifying complex reality by modeling classes appropriate to the
problem, and working at the most appropriate level of inheritance for a given
aspect of the problem.
20
OOP concepts: encapsulation and
information hiding
• Encapsulation refers to the bundling of data members and member functions
inside of a common “box”, thus creating the notion that an object contains its state
as well as its functionalities
• Information hiding refers to the notion of choosing to either expose or hide some
of the members of a class.
• These two concepts are often misidentified. Encapsulation is often understood as
including the notion of information hiding.
• Encapsulation is achieved by specifying which classes may use the members of an
object. The result is that each object exposes to any class a certain interface —
those members accessible to that class.
• The reason for encapsulation is to prevent clients of an interface from depending
on those parts of the implementation that are likely to change in the future,
thereby allowing those changes to be made more easily, that is, without changes
to clients.
• It also aims at preventing unauthorized objects to change the state of an object.
21
OOP concepts: encapsulation and
information hiding
• Members are often specified as public, protected or private, determining whether
they are available to all classes, sub-classes or only the defining class.
– Java uses the default access modifier to restrict access also to classes in the same package
– C# and VB.NET reserve some members to classes in the same assembly using keywords internal (C#)
or friend (VB.NET)
– Eiffel and C++ allow one to specify which classes may access any member of another class (C++
friends)
– Such features are basically overriding the basic information hiding principle, greatly complexify its
implementation, and create confusion when used improperly
22
Procedural Abstraction Contains local
variable declarations
Can be overloaded Can pass arguments and statements
(e.g., binary +) into the scope
slide 24
Arguments and Parameters
• Argument: expression that int h, i;
void B(int w) {
appears in a function call int j, k;
• Parameter: identifier that appears i = 2*w;
w = w+1;
in function declaration }
• Parameter-argument matching by void A(int x, int y) {
bool i, j;
number and position B(h);
– Exception: Perl. Instead of being }
declared in a function header, int main() {
parameters are available as int a, b;
elements of special array @_ h = 5; a = 3; b = 2;
A(a, b);
} slide 25
Parameter Passing Mechanisms
• By value
• By reference
slide 26
Pass by Value
• Caller passes r-value of the argument to function
– Compute the value of the argument at the time of the call
and assign that value to the parameter
– Reduces “aliasing”
• Aliasing: two names refer to the same memory location
• Function cannot change value of caller’s variable
• All arguments in C and Java are passed by value
– To allow caller’s variables to be modified, pointers can be
passed as arguments
• Example: void swap(int *a, int *b) { … }
Is there a contradiction here?
slide 27
Pass by Reference
int h, i;
• Caller passes l-value of the void B(int* w) {
argument to function int j, k;
i = 2*(*w);
– Compute the address of the *w = *w+1;
argument and assign that }
void A(int* x, int* y) {
address to the parameter bool i, j;
– Increases aliasing (why?) B(&h);
}
• Function can modify caller’s int main() {
variable via the address it int a, b;
h = 5; a = 3; b = 2;
received as argument A(&a, &b);
}
slide 28
ML Example
pseudo-code Standard ML
slide 29
Pass by Reference in C++
• Special “reference type” indicates that l-value is passed as argument
– Recall that in C, only r-values can be arguments
• & operator is overloaded in C++
– When applied to a variable, gives its l-value
– When applied to type name in parameter list, means pass the argument by
reference
slide 30
Two Ways To Pass By Reference
C or C++ C++ only
void swap (int *a, int *b) { void swap (int& a, int& b) {
int temp = *a; int temp = a;
*a = *b; a = b;
*b = temp; b = temp;
} }
slide 31
The Pass-by-reference mechanism - the
agreement
• Recall:
32
The Pass-by-reference mechanism - the
agreement (cont.)
• The agreement used in the Pass-by-reference mechanism:
33
The Pass-by-reference mechanism - the
agreement (cont.)
34
The Pass-by-reference mechanism is not
available in Java
• Fact:
35
The Pass-by-reference mechanism - an
hypothetical example
• Example (hypothetical) program:
36
The Pass-by-reference mechanism - an
hypothetical example (cont.)
• When main starts running, it will first create its local
variables:
37
The Pass-by-reference mechanism - an
hypothetical example (cont.)
• We need to know the address of each variable to expose the
details of the pass-by-reference mechanism.
38
The Pass-by-reference mechanism - an
hypothetical example (cont.)
39
The Pass-by-reference mechanism - an
hypothetical example (cont.)
• When execution reaches the method call ToolBox.min(x,y),
the Pass-by-reference mechanism first creates the parameter
variables:
40
The Pass-by-reference mechanism - an
hypothetical example (cont.)
• Then the Pass-by-reference mechanism copies the reference
of the actual parameter to the corresponding formal
parameter:
41
The Pass-by-reference mechanism - an
hypothetical example (cont.)
• Notice that:
42
The Pass-by-reference mechanism - an
hypothetical example (cont.)
• The method invocation mechanism is completed as usually
with the following steps:
43
The Pass-by-reference mechanism - an
hypothetical example (cont.)
44
The Pass-by-reference mechanism - an
hypothetical example (cont.)
• When the min method executes, it will create its local variable m:
45
The Pass-by-reference mechanism - an
hypothetical example (cont.)
• How the called method uses the parameter variables:
46
The Pass-by-reference mechanism - an
hypothetical example (cont.)
47
Illustrating the pass-by-reference mechanism
using C++
• The difference between
• Pass-by-value, and
• Pass-by-reference
48
Illustrating the pass-by-reference mechanism
using C++ (cont.)
• C++ programs of the above examples:
// With & means: pass-by-reference
// No & means: pass-by-value
double fun ( double & a, double & b )
double fun ( double a, double b )
{
{
double m;
double m;
a = a + 1;
a = a + 1;
b = b + 2;
b = b + 2;
m = a + b;
m = a + b;
return(m);
return(m);
}
}
int main(int argc, char **argv)
int main(int argc, char **argv)
{
{
double x = 1.0, y = 4.0;;
double x = 1.0, y = 4.0;;
double r;
double r;
r = fun( x, y );
r = fun( x, y );
cout << x << endl;
cout << x << endl;
cout << y << endl;
cout << y << endl;
cout << r << endl;
cout << r << endl;
}
}
49
Illustrating the pass-by-reference mechanism
using C++ (cont.)
Output: Output:
1 2
4 6
8 8
50
OOP concepts: polymorphism
• The word polymorphism means having many forms.
• In simple words, we can define polymorphism as the ability of a message
to be displayed in more than one form.
• A real-life example of polymorphism, a person at the same time can have
different characteristics. Like a man at the same time is a father, a
husband, an employee. So the same person posses different behavior in
different situations. This is called polymorphism.
• Polymorphism is considered as one of the important features of Object
Oriented Programming.
• polymorphism is mainly divided into two types:
– Compile time Polymorphism
– Runtime Polymorphism
51
52
1. Compile time polymorphism: This type of polymorphism is achieved by function
overloading or operator overloading.
• Function Overloading: When there are multiple functions with same name but
different parameters then these functions are said to be overloaded. Functions can be
overloaded by change in number of arguments or/and change in type of arguments.
• // C++ program for function overloading
class Geeks
{
public:
// function with 1 int parameter
void func(int x)
{
cout << "value of x is " << x << endl;
}
// function with same name but 1 double parameter
void func(double x)
{
cout << "value of x is " << x << endl;
}
// function with same name and 2 int parameters
void func(int x, int y)
{
cout << "value of x and y is " << x << ", " << y << endl;
}
};
53
int main() {
Geeks obj1;
// Which function is called will depend on the parameters passed
// The first 'func' is called
obj1.func(7);
54
2. Operator Overloading:
• C++ also provide option to overload operators.
• For example, we can make the operator (‘+’) for string class to concatenate two strings. We
know that this is the addition operator whose task is to add two operands.
• So a single operator ‘+’ when placed between integer operands , adds them and when placed
between string operands, concatenates them.
• // CPP program to illustrate
• // Operator Overloading
#include<iostream>
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i =0) {real = r; imag = i;}
// This is automatically called when '+' is used with between two Complex objects
Complex operator + (Complex const &obj) {
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag << endl; }
}; 55
int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2; // An example call to "operator+"
c3.print();
}
56
Runtime polymorphism:
• This type of polymorphism is achieved by Function Overriding.
• Function overriding on the other hand occurs when a derived class has a definition for one of the
member functions of the base class. That base function is said to be overridden.
// C++ program for function overriding
#include <bits/stdc++.h>
class base
{
public:
virtual void print ()
{ cout<< "print base class" <<endl; }
void show ()
{ cout<< "show base class" <<endl; }
};
class derived:public base
{
public:
void print () //print () is already virtual function in derived class, we could also declared as virtual void print () explicitly
{ cout<< "print derived class" <<endl; }
void show ()
{ cout<< "show derived class" <<endl; }
};
57
//main function
int main()
{
base *bptr;
derived d;
bptr = &d;
return 0;
}
• Output:
print derived class
show base class
58
Dynamic Memory allocation
• Every program needs storage to be allocated to it for
various purposes.
• When you write a program, you specify what storage
it needs by declaring variables and instances of
classes, e.g:
int a,b,c;
float nums[100];
Circle myCircle(2.0,3,3); etc...
• Then when the program executes, it can make use of
this memory
• It is not possible for variables or objects to be added
during the execution of a program
59
Programs and Memory
• In order to execute a program, it must be loaded into
RAM (Random Access Memory).
• A certain amount of RAM is allocated as the
permanent storage for your program, and this is
where the global variables are stored.
• A dynamic region of memory called the stack is where
local variables are stored.
• This storage is fixed at compile time.
Remember, global variables hold their value for the
lifetime of the program, while local variables only
hold their value for the lifetime of the function they
are declared in. 60
• However, there are times when it is necessary for a
program to make use of variable amounts of storage.
• For example, you may want to write a program that
reads in a list of numbers (until 999 is entered) and
finds their average.
• You may want to store the numbers in an array, but of
what size?
• Each time the program is run, the user may enter any
number of numbers, maybe 5, 50 or 5000.
• One solution is to declare an array of the maximum
size that it could ever be. E.g int nums[10000].
• However, this is wasteful of memory, as you may very
often use only a fraction of the space allocated.
61
• The solution is to use dynamic allocation of memory.
• This is the means by which a program can obtain
memory while it is running.
• Powerful support for dynamic memory allocation is
provided in C++, with the operator new.
• Memory allocated by C++'s dynamic allocation
function is obtained from the heap.
• The heap is a region of free memory area that lies
between your program and its permanent storage
area and the stack.
• C++ also provides the operator delete, which releases
the memory once the program doesn't need it
anymore.
62
The new operator
• The new operator returns a pointer to allocated
memory from the heap.
• It returns a NULL pointer if there is insufficient
memory to fulfill the allocation request.
• The delete operator frees memory previously allocated
using new.
• Example of usage:
int *ptr; //Pointer that can point to an integer
ptr = new int; //Now it points to allocated
memory
63
Example: new
int *ptr; //Pointer that can point to an integer
ptr = new int; //Now it points to allocated memory
66
int *ptr;
int inum; Example:
new with arrays.
cout<<"How many numbers will you enter?: ";
cin>> inum;
if(!ptr)
cout<<" Allocation Error!\n";
else
{
for(int i=0;i<inum;i++)
{
cout<< "Enter number: ";
cin>>ptr[i];
}
/*
* .....Do some processing to the array .......
*/
delete [ ] ptr; //Release 10 elements
}
} 67
OOP: Languages
• Simula (1967) is generally accepted as the first language to have the primary
features of an object-oriented language. It was created for making simulation
programs, in which what came to be called objects were the most important
information representation.
• Smalltalk (1972 to 1980) is arguably the canonical example, and the one with
which much of the theory of object-oriented programming was developed.
68
OOP: Languages
• Concerning the degree of object orientation, following distinction can be made:
– Languages designed mainly for OO programming, but with some procedural elements. Examples: C+
+, C#, Java, Scala, Python.
– Languages that are historically procedural languages, but have been extended with some OO
features. Examples: VB.NET (derived from VB), Fortran 2003, Perl, COBOL 2002, PHP.
– Languages with most of the features of objects (classes, methods, inheritance, reusability), but in a
distinctly original form. Examples: Oberon (Oberon-1 or Oberon-2).
– Languages with abstract data type support, but not all features of object-orientation, sometimes
called object-based languages. Examples: Modula-2, Pliant, CLU.
69
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
1-70
The Exclusivity of Objects
• Everything is an object
– Advantage - elegance and purity
– Disadvantage - slow operations on simple objects
• Add objects to a complete typing system
– Advantage - fast operations on simple objects
– Disadvantage - results in a confusing type system (two kinds of
entities)
• Include an imperative-style typing system for primitives but
make everything else objects
– Advantage - fast operations on simple objects and a relatively small
typing system
– Disadvantage - still some confusion because of the two type systems
1-71
Are Subclasses Subtypes?
• Does an “is-a” relationship hold between a
parent class object and an object of the
subclass?
– If a derived class is-a parent class, then objects of
the derived class must behave the same as the
parent class object
• A derived class is a subtype if it has an is-a
relationship with its parent class
– Subclass can only add variables and methods and
override inherited methods in “compatible” ways
1-72
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
• If overriding methods are restricted to having
the same parameter types and return type,
the checking can be static
1-73
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 (in part
due to name collisions)
– Potential inefficiency - dynamic binding costs more
with multiple inheritance (but not much)
• Advantage:
– Sometimes it is quite convenient and valuable
1-74
Allocation and DeAllocation of Objects
1-76
Nested Classes
• If a new class is needed by only one class, there
is no reason to define so it can 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
1-77
1-78
Initialization of Objects
• Are objects initialized to values when they are
created?
– Implicit or explicit initialization
1-79
Support for OOP in Smalltalk
• Smalltalk is a pure OOP language
– Everything is an object
– All objects have local memory
– All computation is through objects sending
messages to objects
– None of the appearances of imperative languages
– All objected are allocated from the heap
– All deallocation is implicit
1-80
Support for OOP in Smalltalk (continued)
• Type Checking and Polymorphism
– All binding of messages to methods is dynamic
• The process is to search the object to which the
message is sent for the method; if not found, search
the superclass, etc. up to the system class which has
no superclass
– The only type checking in Smalltalk is dynamic
and the only type error occurs when a message is
sent to an object that has no matching method
1-81
Support for OOP in Smalltalk (continued)
• Inheritance
– A Smalltalk subclass inherits all of the instance
variables, instance methods, and class methods of
its superclass
– All subclasses are subtypes (nothing can be
hidden)
– All inheritance is implementation inheritance
– No multiple inheritance
1-82
Support for OOP in Smalltalk (continued)
• Evaluation of Smalltalk
– The syntax of the language is simple and regular
– Good example of power provided by a small
language
– Slow compared with conventional compiled
imperative languages
– Dynamic binding allows type errors to go
undetected until run time
– Introduced the graphical user interface
– Greatest impact: advancement of OOP
1-83
Support for OOP in C++
• General Characteristics:
– Evolved from C and SIMULA 67
– Among the most widely used OOP languages
– Mixed typing system
– Constructors and destructors
– Elaborate access controls to class entities
1-84
Support for OOP in C++ (continued)
• Inheritance
– A class need not be the subclass of any class
– Access controls for members are
– Private (visible only in the class and friends)
(disallows subclasses from being subtypes)
– Public (visible in subclasses and clients)
– Protected (visible in the class and in subclasses, but
not clients)
1-85
Support for OOP in C++ (continued)
1-86
Inheritance Example in C++
class base_class {
private:
int a;
float x;
protected:
int b;
float y;
public:
int c;
float z;
};
1-87
Reexportation in C++
• A member that is not accessible in a subclass
(because of private derivation) can be
declared to be visible there using the scope
resolution operator (::), e.g.,
class subclass_3 : private base_class {
base_class :: c;
…
}
1-88
Reexportation (continued)
• One motivation for using private derivation
– A class provides members that must be visible, so
they are defined to be public members; a derived
class adds some new members, but does not
want its clients to see the members of the parent
class, even though they had to be public in the
parent class definition
1-89
Support for OOP in C++ (continued)
1-90
Support for OOP in C++ (continued)
• Dynamic Binding
– A method can be defined to be virtual, which
means that they 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
is an abstract class
1-91
Support for OOP in C++ (continued)
• Evaluation
– C++ provides extensive access controls (unlike
Smalltalk)
– C++ provides multiple inheritance
– In C++, the programmer must decide at design time
which methods will be statically bound and which
must be dynamically bound
• Static binding is faster!
– Smalltalk type checking is dynamic (flexible, but
somewhat unsafe)
– Because of interpretation and dynamic binding,
Smalltalk is ~10 times slower than C++
1-92
Support for OOP in Java
• Because of its close relationship to C++, focus is on the
differences from that language
• General Characteristics
– All data are objects except the primitive types
– All primitive types have wrapper classes that store one data value
– All objects are heap-dynamic, are referenced through reference
variables, and most are allocated with new
– A finalize method is implicitly called when the garbage collector
is about to reclaim the storage occupied by the object
1-93
Support for OOP in Java (continued)
• Inheritance
– Single inheritance supported only, but there is an
abstract class category that provides some of the
benefits of multiple inheritance (interface)
– An interface can include only method declarations and
named constants, e.g.,
public interface Comparable <T> {
public int comparedTo (T b);
}
– Methods can be final (cannot be overriden)
1-94
Support for OOP in Java (continued)
• Dynamic Binding
– In Java, all messages are dynamically bound to
methods, unless the method is final (i.e., it
cannot be overriden, therefore dynamic binding
serves no purpose)
– Static binding is also used if the methods is
static or private both of which disallow
overriding
1-95
Support for OOP in Java (continued)
• 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
– A static nested class cannot access members of its nesting class
• Nested classes can be anonymous
• A local nested class is defined in a method of its nesting class
– No access specifier is used
1-96
Support for OOP in Java (continued)
• Evaluation
– 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
1-97
Support for OOP in C#
• General characteristics
– Support for OOP similar to Java
– Includes both classes and structs
– Classes are similar to Java’s classes
– structs are less powerful stack-dynamic
constructs (e.g., no inheritance)
1-98
Support for OOP in C# (continued)
• Inheritance
– Uses the syntax of C++ for defining classes
– A method inherited from parent class can be
replaced in the derived class by marking its
definition with new
– The parent class version can still be called
explicitly with the prefix base:
base.Draw()
1-99
Support for OOP in C#
• Dynamic binding
– To allow dynamic binding of method calls to
methods:
• The base class method is marked virtual
• The corresponding methods in derived classes are
marked override
– Abstract methods are marked abstract and
must be implemented in all subclasses
– All C# classes are ultimately deri ved from a single
root class, Object
1-100
Support for OOP in C# (continued)
• Nested Classes
– A C# class that is directly nested in a nesting class
behaves like a Java static nested class
– C# does not support nested classes that behave
like the non-static classes of Java
1-101
Support for OOP in C#
• Evaluation
– C# is the most recently designed C-based OO
language
– The differences between C#’s and Java’s support
for OOP are relatively minor
1-102
Support for OOP in Ada 95
• General Characteristics
– OOP was one of the most important extensions to
Ada 83
– Encapsulation container is a package that defines a
tagged type
– A tagged type is one in which every object includes
a tag to indicate during execution its type (the tags
are internal)
– Tagged types can be either private types or records
– No constructors or destructors are implicitly called
1-103
Support for OOP in Ada 95 (continued)
• Inheritance
– Subclasses can be derived from tagged types
– New entities are added to the inherited entities by
placing them in a record definition
– All subclasses are subtypes
– No support for multiple inheritance
• A comparable effect can be achieved using generic
classes
1-104
Example of a Tagged Type
Package Person_Pkg is
type Person is tagged private;
procedure Display(P : in out Person);
private
type Person is tagged
record
Name : String(1..30);
Address : String(1..30);
Age : Integer;
end record;
end Person_Pkg;
with Person_Pkg; use Person_Pkg;
package Student_Pkg is
type Student is new Person with
record
Grade_Point_Average : Float;
Grade_Level : Integer;
end record;
procedure Display (St: in Student);
end Student_Pkg;
1-105
Support for OOP in Ada 95 (continued)
• Dynamic Binding
– Dynamic binding is done using polymorphic
variables called classwide types
• For the tagged type Prtdon, the classwide type is
Person‘ class
– Other bindings are static
– Any method may be dynamically bound
– Purely abstract base types can be defined in Ada
95 by including the reserved word abstract
1-106
Support for OOP in Ada 95 (continued)
• Evaluation
– Ada offers complete support for OOP
– C++ offers better form of inheritance than Ada
– Ada includes no initialization of objects (e.g.,
constructors)
– Dynamic binding in C-based OOP languages is
restricted to pointers and/or references to objects;
Ada has no such restriction and is thus more
orthogonal
1-107
Support for OOP in Ruby
• General Characteristics
– Everything is an object
– 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
– Getters and setters can be defined by shortcuts
1-108
Support for OOP in Ruby (continued)
• Inheritance
– Access control to inherited methods can be different
than in the parent class
– Subclasses are not necessarily subtypes
– Mixins can be created with modules,
providing a kind of multiple inheritance
• Dynamic Binding
– All variables are typeless and polymorphic
• Evaluation
– Does not support abstract classes
– Does not fully support multiple inheritance
– Access controls are weaker than those of other
languages that support OOP
1-109
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
• Smalltalk is a pure OOL
• C++ has two distinct type system (hybrid)
• Java is not a hybrid language like C++; it supports only OO programming
• C# is based on C++ and Java
• Ruby is a new pure OOP language; provides some new ideas in support for
OOP
• JavaScript is not an OOP language but provides interesting variations
• Implementing OOP involves some new data structures
1-110