0% found this document useful (0 votes)
13 views

Unit1 - OOP and Demo

Uploaded by

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

Unit1 - OOP and Demo

Uploaded by

santhosh kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 67

SRM Institute of Science and Technology

Advanced Programming Practice-18CSC207J

Unit 1
Overview of the Unit

 Structured Programming Paradigm

 Procedural Programming Paradigm

 Object Oriented Programming Paradigm


3. Object-Oriented Programming
Session 11-15 covers the following Topics:-
 Object Oriented Programming Paradigm
 Class, Objects, Instances, Methods
 Encapsulation, Data Abstraction
 Polymorphism, Inheritance
 Constructor, Destructor
 Example Languages: BETA, Cecil, Lava.
 Demo: OOP in Python
 Lab 3: Object Oriented Programming
Text Book: Shalom, Elad. A Review of Programming
Paradigms Throughout the History: With a Suggestion Toward
Object-Oriented Programming

 Based on the concept of objects - attributes


and methods. Objects are instances of classes which
interact with one another.
 OOP treat data as a critical element in the program
development and does not allow it to flow freely around the
system.
 It ties data more closely to the functions that operate on it,
and protects it from accidental modification from outside
Overview
 Object-oriented programming attempts to provide a
model for programming based on objects.

 Objects are designed in class hierarchies.

 Merges abstract data types with structured programming


and divides systems into modular objects
whichown their own data and are responsible for their
own behavior. This feature is known as
encapsulation.

 The construct that combines data with a set of


methods for accessing and managing data is calledan
object.
Concepts - Objects and reference
variables
STATEMENT VISUAL PICTURIZATION

int x X

Not a X= 45 X 45 String
primitive Object
data type Stringstr; str = “Java”
1050 Java
str = new Str 1050
String(“Java”);
String Instances
Reference Operato
r Object of Class
Variable
String
Hence..
 While working with classes

 Reference variable of a class type is declared

 An object is instantiated and its address is


stored into the reference variable.

 Two types of variables can be declared in Java: primitive


type variables and reference variables.

 Primitive type variables store data directly into their own


memory spaces while Reference variables store the
address of the object containing the data.

 In some languages, such as C++, reference variables -


Methods – overview and predefined

methods
A method in object-oriented programming is a
procedure associated with an object class.
 A simple example would be a window object
that has methods open and close.
 Overriding is a feature that allows a
subclass or child class to provide a specific
implementation of a method that is already
provided by one of its superclasses or parent classes.
Version of method is based on Object.
 Methods also provide the interface that other classes
use to access and modify the data properties of an
object. This is known as encapsulation.
 A class is a collection of methods and data
members.
Advantages -Method
 While working on one method, you can focus
on just that part of the program and
construct it, debug it, and perfect it.
 Different people can work on different
methods simultaneously.
 If a method is needed in more than
one place in a program, or in different
programs, it can be written once and used
many times. - reuse
 Using methods greatly enhances the program’s
readability because it reduces the complexity of
the method main.
 Methods are also known as Modules
 Every method has a name and, depending on the
values specified by the user, it does some
computation.
Return type double pow(x,y
) Parameter or
argument

 Predefined methods in Java are organized as a


collection of classes, calledclass libraries.
 For example, the class Math contains
mathematical methods and it is contained in
the package java.lang.
 By default, //to use
Java automatically any imports
static method
classesof
import java.util.*; the class
from Wildcard
the package importjava.lang.
static packageName.ClassName.*;

Math.methodName(parameters); //to use a specific static method


of the class
import static
packageName.ClassName.methodName;
Methods – Final Note
 To use methods, it is important to know
the following properties
 the name of the method
 the number of parameters, if any
 the datatypeof each parameter
 The datatypeof the value computed (the
value returned) by the method, called the type
of the method
Methods – user-defined methods
and method overloading
 User-defined methods in Java are classified into
two categories:

 value-returning methods – methods that have a


return data type; these methods return a value
of a specific data type using the return statement.

 Example: pow , sqrt , isLowerCase, toUpperCase

 void methods – methods that do not have a


return data type; these methods do not use a
return statement to return a value.
Formal Vs Actual Parameter
public static int abs(int number)
Formal
parameter
{
if(number < 0)
number = -number;
return number;
}
Actual parameter
int n = abs(-15);

Formal parameter: A variable declared in


the method heading.
Actual parameter: A variable or expression
listed in a call to a method.
Method - Components
public static double larger(double x,
double y)
{
double max;
if(x >= y)
{
max = x;
}
else
max = y;
return max;
}
Method - Components
public static double larger(double x,
Modifier double y)
Method type Formal
{ parameter
Method
Local double max; name
declaration
if(x >= y)
{ Modifier
max = x; • Public
• private
} •
else protected
max Expression
= y; • static
• abstract
return max; • final
}
Method overload
 In Java, several methods can have the same name within
a class. This is called method overloading.
 Overloading the method methodXYZ
 public void methodXYZ()
 public void methodXYZ(int x, double y)
 public void methodXYZ(double one, int y)
CORRECT
 public void methodXYZ(int x, double y, char c)

 public void methodABC(int x, double y)


WRONG
 public int methodABS(int x, double y)
Example

int larger(int x, int y)

char larger(char first, char second)

double larger(double u, double v)

Stringlarger(String first, Stringsecond)

larger(5, 3)

larger(‘A’, ‘9’),
Classes and instances
 Class is an extensible program-code template for
 Creating objects,
 Providing initial values for state
 Implementations of behavior
 When a constructor creates an object, that
object is calledan instance of the class.
 The creation of an instance is calledinstantiation.

 Not all classes can be instantiated, like abstract


classes, while those that can be instantiated are
called concrete classes.
 After instantiation, the member variables specific to
the object are calledinstance variables, to contrast
with the class variables shared across the class.
Setters
or
mutato
r
Getter
or
accesso
r
CONSTRUCTOR
 The name of a constructor is the sameas the
name of the class.
 A constructor, even though it is a method,
has no return type. That is, it is neither a
value-returning method nor a void method.
 A class can have more than one constructor. - Overloaded.
 If a class has more than one constructor, the
constructors must have different signatures.
 Constructors execute automatically when objects are
instantiated.
 If there are multiple constructors, the constructor that
executes depends on the type values passed
to the class object when the class object is
instantiated.
Basic Concepts of OOP

 Objects
Object : CUSTOMER Object : ACCOUNT

DATA DATA
AC No. AC No.
Name of AC Holder AC Balance
Address Type of Account

FUNCTIONS FUNCTIONS
Deposit Account Balance
Withdrawal
AC Balance Display
Basic Concepts of OOP
 Classes
Classes are user-defined data types.

The entire set of data and code of an object can be made a user-defined data
type with the help of a class. Objects are variables of the type class. Once
a class has been defined, we can create any number of objects belonging
to that class. Each object is associated with the data of type class with
which they are created.

A class is a collection of objects of similar type.


Basic Concepts of OOP

 Classes

If fruit has been defined as a class, then the statement

fruit mango;

will create an object mango belonging to the class fruit.


 Data Abstraction and Encapsulation
o The wrapping up of data and functions into a single unit
is known as encapsulation.

o The data is not accessible to the outside world, and only


those functions which are wrapped in the class can access
it.

o These functions provide the interface between the object’s


data and the program. This insulation of the data from
direct access by the program is called data hiding or
information hiding.
 Data Abstraction and Encapsulation

The attributes wrapped in the classes are called data


members and the functions that operate on these data are
called methods or member functions.

Since the classes use the concept of data abstraction, they


are known as Abstracted Data Types (ADT).
 Inheritance
o Inheritance is the process by which objects of one class acquire
the properties of objects of another class.

o It supports the concept of hierarchical classification.

o Each derived class shares common characteristics with the class


from which it is derived.
Property Inheritance
Bird
Attributes:
Feathers
Lay eggs

Flying Bird Non-flying Bird

Attributes: Attributes:
------------ ------------
------------ ------------

Robin Swallow Penguin Kiwi


Attributes: Attributes: Attributes: Attributes:
------------ ------------ ------------ ------------
------------ ------------ ------------ ------------
 Inheritance
o Inheritance provides the idea of reusability.

o We can add additional features to an existing class without


modifying it.
(By deriving new class from existing one. The new class will
have the combined features of both the classes.)
 Polymorphism - ability to take more than one form
o An operation may exhibit different behaviours in different
instances.
o The behaviour depends upon the types of data used in the
operation.
o add( 3, 5) gives 8
o Add(“hello”, “-world”) gives “hello-world”
 Polymorphism - ability to take more than one form
o The process of making an operator to exhibit different behaviours in
different instances is known as operator overloading.
o << Insertion Operator
o << Left-shift bit-wise operator
o Using a single function name to perform different types of tasks is known as
function overloading.
o add( 3, 5) gives 8
o Add(“hello”, “-world”) gives “hello-world”
 Dynamic Binding
Binding refers to the linking of a procedure call to the
code to be executed in response to the call.

Dynamic binding ( late binding ) means that the code


associated with a given procedure call is not known
until the time of the call at run-time.

It is associated with polymorphism and inheritance.


 Message Passing
o An oop consists of a set of objects that communicate with
each other.
o Oop involves the following steps:
o Creating classes that define objects and their behaviour.
o Creating objects from class definitions.
o Establishing communication among objects.
o Objects communicate with one another by sending and
receiving information.
 Message Passing
o A message for an object is a request for execution of a
procedure.
o The receiving object will invoke a function and generates
results.
o Message passing involves specifying:
o The name of the Object.
o The name of the Function.
o The information to be send.
Benefits of OOP
 Inheritance – eliminate redundant code and
extend the use of existing classes.
 We can build programs from the standard
working module, no need of starting from the
scratch.
 Data hiding helps the programmer to build
secure programs that can not be invaded by
code in other parts of the program.
 Multiple instances of an objects can co-exists with out
any interference.
 It is easy to partition the work in a project based on
objects.
 Object-oriented system can be easily upgraded from
small to large systems.
 Message passing techniques for communication between
objects makes the interface descriptions with external
systems much simpler.
 Software complexity can be easily managed.
INTRODUCTION TO OOPS IN PYTHON

Python is a multi-paradigm programming language. Meaning, it supports different


programming approach.
One of the popular approach to solve a programming problem is by creating
objects. This is known as Object-Oriented Programming (OOP).
An object has two characteristics:
• attributes
• behavior
Let's take an example:
Student is an object,
name, age, gender are attributes
singing, dancing are behavior
OBJECT-ORIENTED PROGRAMMING
 OOP treat data as a critical element in the program development
and does not allow it to flow freely around the system.
 It ties data more closely to the functions that operate on it, and
protects it from accidental modification from outside functions.
 OOP allows decomposition of a problem into a number of entities
called objects and then build data functions around these objects.
 The data of an object can be accessed only by the functions
associated with that object.
 Functions of one object can access the functions of another objects
ORGANIZATION OF DATA AND FUNCTIONS IN OOP

Object A Object B

Data Data

Communication
Functions Functions

Object C

Data

Functions
CHARACTERISTICS OF OBJECT-ORIENTED
PROGRAMMING

 Emphasis is on data rather than procedure.


 Programs are divided into objects.
 Data structures are designed such that they characterize the objects.
 Functions that operate on the data of an object are tied together in the
data structure.
 Data is hidden and can not be accessed by external functions.
 Objects may communicate with each other through functions.
 New data and functions can be added easily whenever necessary.
 Follows bottom-up approach in program design.
 The concept of OOP in Python focuses on creating reusable code. In Python, the
concept of OOP follows some basic principles:

 Inheritance A process of using details from a new class without


modifying existing class.

 Encapsulation Hiding the private details of a class from other objects.

 Polymorphism A concept of using common operation in different ways for


different data input.
CLASS
 A class is a blueprint for the object or user defined data type.
 It contains all the details about the name, gender, size etc. Based on these descriptions ,Here,
Student is an object.
 The example for class of Student can be :
class Student:
Here, we use class keyword to define an empty class Student. From class, we construct
instances. An instance is a specific object created from a particular class.
OBJECT
 An object (instance) is an instantiation of a class. When class is defined, only the description for
the object is defined. Therefore, no memory or storage is allocated.
 The example for object of Student class can be:
obj = Student()
Here, obj is object of class Student.
Suppose we have details of Student. Now, we are going to show how to build the class and objects of
Student.
EXAMPLE FOR CLASS & OBJECT

OUTPUT
METHODS
Methods are functions defined inside the body of a class. They are used to define the
behaviors of an object.
METHODS
Methods are functions defined inside the body of a class. They are used to define the
behaviors of an object.
INHERITANCE
Inheritance is a way of creating new class for using details of existing class without
modifying it. The newly formed class is a derived class (or child class). Similarly, the
existing class is a base class (or parent class).
SINGLE INHERITANCE

 Child class inherits only a single parent class


MULTIPLE INHERITANCE

 Child class inherits from more than one parent class


MULTILEVEL INHERITANCE
 Child class inherits from another child class
HIERARCHICAL INHERITANCE

 Many children from same parent class


HYBRID INHERITANCE

 Combination of above mentioned types


HYBRID – WRONG EXAMPLE
Super () IN PYTHON

 A child class calls the method of immediate parent


OVERRIDING

 Functionality of a parent class is updated by child class


INHERITANCE – OVERRIDE , SUPER , CONSTRUCTOR

PRIVAT
E

UPDATE

EXTEND

INHERI
T
DATA ENCAPSULATION IN PYTHON
POLYMORPHISM
PARAMETRIZED CONSTRUCTOR
DESTRUCTORS IN PYTHON

Destructors are called when an object gets destroyed. In Python, destructors are not needed as
much needed in C++ because Python has a garbage collector that handles memory management
automatically. The __del__() method is a known as a destructor method in Python.
Python - public, private and protected Access
Modifiers
 All members in a Python class are public by default.
Any member can be accessed from outside the class
environment.
 Example: Public Attributes
 class employee:
def __init__(self, name, sal):
self.name=name
self.salary=sal
 Python's convention to make an instance variable
protected is to add a prefix _ (single underscore) to
it. This effectively prevents it to be accessed, unless it
is from within a sub-class.

 Example: Protected Attributes


class employee:
def __init__(self, name, sal):
self._name=name # protected attribute
self._salary=sal # protected attribute
 Similarly, a double underscore __ prefixed to a
variable makes it private. It gives a strong suggestion
not to touch it from outside the class. Any attempt to
do so will result in an AttributeError:

 Example: Private Attributes


 class employee:
 def __init__(self, name, sal):
 self.__name=name # private attribute
 self.__salary=sal # private attribute
RECAP

 Public – no underscore E.g.: self.name


 Protected – single underscore E.g.: self._name
 Private – double underscore E.g.:
self.__name
PUBLIC MODIFIER
PROTECTED MODIFIER
PROTECTED MODIFIER
PRIVATE
MODIFIER

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy