Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Chapter 1 - Principal of Object Oriented Programming

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

College of Business, Science &Technology (CBST), Mymensingh

Department of Computer Science and Engineering

Object Oriented Programming (OOP)

Principles of Object Oriented Programming

Prepared by
Md. Masum Billah
Lecturer, Dept. of CSE, CBST
Mobile: 01793200796
Q. What is Programming?
Programming is the process of designing, writing, testing, and maintaining computer programs to solve
problems.
Programs can be used to automate tasks, process data, control hardware, build websites and mobile
applications, create video games, and perform many other functions.

Q 2. Define Procedural oriented programming and write down the characteristics of


procedural oriented programming.
Procedural oriented programming (pop)
Procedural-oriented programming (POP) is a programming paradigm that focuses on the procedures or
functions that operate on data. In POP, a program is divided into smaller procedures or functions that can
be called to perform specific tasks.

Example: c, basic, FORTRAN.

Characteristics of Procedural oriented programming

1. It focuses on procedures or functions that operate on data.


2. A program is divided into a number of functions and each function has clearly defined purpose.
3. Most of the functions share global data.
4. Data moves openly around the system from function to function.
5. It follows top-down approach. Where the program starts with the main function and then calls other
functions as needed.

Q. Describe how data are shared by functions in a procedure oriented programs.


In procedure oriented program many important data items are placed as global so that they can be
accessed by all the functions. Each function may have its own local data. Global data are more vulnerable
to an unintended change by a function. Through the use of global variable, data is shared among
functions in procedure oriented programs.
Fig: Organization of data and function in POP

Q 1. Define Object oriented programming. Write the benefits of Object Oriented


Programming?
Object Oriented Programming

Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around
objects rather than functions and logic. An object is an instance of a class, which can contain both data
(attributes or properties) and methods (functions or behaviors).

The benefits of Object-Oriented Programming (OOP) are given below briefly:

1. Modularity: Breaks down large programs into manageable objects, improving organization and code
clarity.

2. Reusability: Encourages code reuse through inheritance and libraries, reducing redundancy and
development time.

3. Encapsulation: Protects data by restricting access, enhancing security and data integrity.

4. Productivity: Increases development efficiency through reusable objects and modular design.

5. Real-World Mapping: Models real-world entities, making design intuitive and easier to understand.

6. Flexibility: Supports polymorphism, allowing flexible and efficient code management.

7. Scalability: Eases modification and extension of code, making software adaptable and maintainable
Q 3. Write down the difference between Procedure Oriented Programming(POP)
and Object Oriented Programming(OOP).
Or, How does Object oriented approach differ from Procedure oriented approach?
Difference between Procedure Oriented Programming and Object Oriented Programming

are as following- Object-Oriented Programming (OOP):

Procedure-Oriented Programming
Feature Object-Oriented Programming (OOP)
(POP)

Focuses on objects that combine data and


Basic Concept Focuses on functions or procedures
methods

Data and Function Functions operate on data passed as Data and methods are encapsulated within
Relation arguments objects

Achieved through functions, with Achieved through classes and objects,


Modularity
risk of global data access promoting encapsulation

Reusability via functions, less Enhanced reusability through inheritance,


Reusability
emphasis on data structures polymorphism, and encapsulation

No inheritance; code duplication


Inheritance Supports inheritance, reducing redundancy
may occur

Data hiding is a core feature, restricting


Data Hiding No built-in data hiding
external access

Problem Solving Tasks are broken down into Models real-world entities as objects that
Approach sequences of functions interact

Examples C, Fortran, Pascal Java, C++, Python, Ruby

Simpler for linear tasks, harder to


Flexibility Better suited for complex, scalable systems
scale

Q 4. Basic Organization of data and function in an Object Oriented Programming.


Or, Describe how data are shared by functions in an Object Oriented Programs.
Object oriented programming is an approach that provides a way of modularization program by creating
objects. Object is considered to be a module with data and set of operations that can access that data.
Since for each object memory is allocated separately. Through function calling objects can share data
among them.
Fig- Organization of data and function in OOP.

Q 5. What the striking features are of object oriented programming?


Striking features of object oriented programming

1. Emphasis is on data rather than procedure.


2. Programs are divided into objects.
3. Data structures are designed such that they characterize the object.
4. Functions that operate on the data of an object are tied together in the data structure.
5. Data is hidden & cannot be accessed by external functions.
6. Objects may communicate with each other through functions.
7. New data and functions can be easily added whenever necessary.
8. Follow bottom-up approach. This means starting with the smaller building blocks of a system,
such as classes and functions, and then gradually building up to the larger system.

Q 6. Difference between Structured Programming and Object Oriented


Programming.

Structured Programming (SP) and Object-Oriented Programming (OOP) are two distinct programming
paradigms, each with its own approach to organizing and managing code. Here's a comparison of the two:

Feature Structured Programming (SP) Object-Oriented Programming (OOP)

Focuses on a logical structure with


Focuses on objects that combine data and
Basic Concept sequence, selection, and iteration to
methods, modeling real-world entities.
control the flow of the program.

Program Organized around functions and Organized around objects and classes that
Organization procedures that operate on data. encapsulate data and methods.

Data is typically global or passed through Data is encapsulated within objects,


Data Handling
functions. providing better security and data integrity.

Reusability is limited to functions and


Promotes reusability through inheritance,
Reusability procedures. Code often needs to be
polymorphism, and object composition.
rewritten for similar tasks.
Feature Structured Programming (SP) Object-Oriented Programming (OOP)

Less scalable; adding new features often More scalable; new features can be added
Scalability requires significant changes to existing with minimal changes by extending classes
code. or adding new objects.

Examples C, Pascal, Fortran Java, C++, Python, Ruby

Best for small to medium-sized tasks with Better suited for complex, large-scale
Flexibility
clear, linear logic. systems where objects interact.

Q. Write down the application areas of OOP.


Object-Oriented Programming revolutionized the way we solve a problem with computer program. It is
used to solve complex problems. It has also got importance in real business systems as they are very
complicated and use many methods, and OOP can simplify those.

Main application areas of OOP are:


 User interface design such as windows, menu.
 Real Time Systems Design.
 Simulation and Modeling system.
 Object oriented database.
 Object oriented Distributed database.
 Client Server System.
 Hypertext, Hypermedia.
 AI and Expert System
 Neural Networks and parallel programming.
 Decision support and office automation systems.

Q 8. Describe the major part of C++ Programming Language.

From any reference book

Q 9. Difference between Object Based and Object Oriented Language.


Aspect Object-Based Language Object-Oriented Language

Uses objects, but doesn’t support Fully supports all features of object-oriented
Definition
all OOP features. programming (OOP).

No inheritance (classes can't pass Supports inheritance (classes can pass traits to
Inheritance
traits to others). others).

Supports polymorphism (objects can behave


Polymorphism Not supported.
differently in different contexts).

Main OOP Only encapsulation and Supports encapsulation, inheritance,


Aspect Object-Based Language Object-Oriented Language

Features abstraction. polymorphism, and abstraction.

Examples Early JavaScript, VBScript. C++, Java, Python.

Q 10. What is Abstract Data Type(ADT)?

An Abstract Data Type (ADT)is like a blueprint for a data structure that defines what we can do with the
data but hides how it's done. It specifies the operations we can perform (like adding, removing, or
checking data), without showing how the data is stored or managed internally.

Example:
Think of a stack:
- we can push items onto it, pop items off, and peek at the top item.
- we don’t need to know how the stack is stored inside (it could be an array or a list); you just use it based
on the available operations.

An ADT focuses on ‘what’ operations are available, not ‘how’ they work internally.

Q 11. Difference between Data Abstraction and Data Encapsulation.


Aspect Data Abstraction Data Encapsulation

Hiding the internal details and showing Bundling data and methods that operate on the
Definition
only the essential features. data into a single unit and restricting access.

Focus What an object does (functionality). How data is protected and managed.

To reduce complexity by simplifying the


Purpose To protect data and ensure controlled access.
interface.

Achieved Abstract classes, interfaces, and function Classes with access specifiers (private,
Through declarations. protected, public).

Access to Not concerned with restricting data Controls access to data by restricting direct
Data access directly. manipulation.

To highlight relevant data and hide To safeguard the internal state and ensure data
Goal
unnecessary details. integrity.

Abstracting a car's functionality (drive, Encapsulating a bank account's balance and


Example
stop) without showing engine details. restricting its direct modification.

Q 12. What is Reusability? How do you achieve this in C++.


Reusability refers to the ability to use components (like code, libraries, functions, or classes) in multiple
programs or contexts without significant modification. It is a key concept in software engineering, as it
helps reduce duplication, improve maintainability, and accelerate development. Code that is reusable is
modular, generalized, and can be adapted to different tasks with little effort.

In C++, reusability can be achieved through:

1. Functions: Encapsulating functionality for reuse.


2. Classes: Creating objects to reuse across programs.
3. Inheritance: Sharing behavior between classes.
4. Templates: Writing generic code for multiple data types.
5. Libraries (STL): Using pre-built reusable components.
6. Namespaces: Organizing and reusing code without conflicts.
7. Polymorphism: Using base class interfaces for flexible reuse.

These techniques allow developers to write modular, adaptable, and maintainable code.

Q 13. Define System Design. Explain briefly steps involved in Object Oriented Design
Approach.
System Design refers to the process of defining the architecture, components, interfaces, and data for a
system to satisfy specified requirements. It involves designing how different parts of the system interact
with each other, ensuring the system is scalable, efficient, and meets the needs of the users.

Steps in Object-Oriented Design (OOD) Approach:

Identify the Objects: Determine the key objects (or classes) that are relevant to the problem domain.
Objects represent real-world entities or concepts within the system.

Define the Attributes and Methods: For each object, specify its attributes (data) and methods (functions)
that define its behavior. This step involves detailing what the object knows and what it can do.

Establish Relationships: Identify how the objects are related to each other. This includes defining
associations (how objects interact), inheritance (how objects share common features), and aggregation
(how objects are composed of other objects).

Design Class Hierarchies: Organize the objects into a hierarchy based on common traits. Use
inheritance to create a structured classification where child classes inherit features from parent classes.

Create Interaction Diagrams: Develop diagrams (like sequence or collaboration diagrams) to visualize
how objects interact with each other to perform specific tasks or processes. This helps in understanding
the flow of data and control within the system.

Q 14. Difference between Object and Class.

Object Class
Object is an instance of a class. Class is a blueprint or template from which
objects are created.

Object is a real world entity such as pen, laptop, Class is a group of similar objects.
mobile, bed, keyboard, mouse, chair etc.

Object is a physical entity. Class is a logical entity.

Object is created through new keyword mainly e.g. Class is declared using class keyword e.g.
Student s1=new Student(); class Student{}

Object is created many times as per requirement. Class is declared once.

Object allocates memory when it is created. Class doesn't allocated memory when it is
created.

There are many ways to create object in java such There is only one way to define class in java using
as new keyword, newInstance() method, clone() class keyword.
method, factory method and deserialization.

Q 15. Distinguished between Inheritance and Polymorphism.

Inheritance Polymorphism
Inheritance is one in which a new class is created
Whereas polymorphism is that which can be
(derived class) that inherits the features from the
defined in multiple forms.
already existing class(Base class).
Whereas it is basically applied to functions or
It is basically applied to classes.
methods.
Inheritance supports the concept of reusability and Polymorphism allows the object to decide which
reduces code length in object-oriented form of the function to implement at compile-time
programming. (overloading) as well as run-time (overriding).
Whereas it can be compiled-time polymorphism
Inheritance can be single, hybrid, multiple,
(overload) as well as run-time polymorphism
hierarchical and multilevel inheritance.
(overriding).
It is used in pattern designing. While it is also used in pattern designing.
Example : Example :
The class bike can be inherit from the class of The class bike can have method name set_color(),
two-wheel vehicles, which is turn could be a which changes the bike’s color based on the name
subclass of vehicles. of color you have entered.

Q 16. What do you mean by Dynamic Binding? How is it useful in OOP?


Dynamic Binding (also known as Late Binding) refers to the process of linking a function call to the
code that will be executed only at runtime, rather than at compile-time. In object-oriented programming
(OOP), this is typically associated with polymorphism and is often used when dealing with inheritance
and virtual functions.

Benefits of Dynamic Binding in OOP


1. Polymorphism: Dynamic binding is a key enabler of polymorphism, one of the core principles of
OOP. It allows objects of different classes to be treated as objects of a common base class, but still
behave according to their actual derived types.

2. Extensibility: Dynamic binding allows new derived classes to be added with minimal changes to
existing code. The base class functions can be overridden in derived classes to provide specific
functionality, and dynamic binding ensures that the correct function is called based on the object's type.

3. Code Reusability: It allows for writing more generic and reusable code. we can write code that works
with pointers or references to the base class, and it will automatically work with any derived class that
overrides the base class's virtual functions.

4. Maintainability: By reducing the need for conditional statements (like if-else or switch), dynamic
binding makes code cleaner and easier to maintain.

Q 17. Explain the Data Types in C++.



1. Primary Data Types

These are the fundamental types provided by the C/C++ language. They include:

 Integer: Represents whole numbers (e.g., int).


 Character: Used to store single characters (e.g., char).
 Boolean: Used to store true or false values (e.g., bool).
 Floating Point: Used for single-precision floating-point numbers (e.g., float).
 Double Floating Point: Used for double-precision floating-point numbers (e.g., double).
 Void: Represents the absence of a type. Often used for functions that do not return a value.
 Wide Character: Used to store wide characters (e.g., wchar_t).

2. Derived Data Types


These types are derived from the primary data types. They include:

 Function: Represents a block of code that performs a specific task and can return a value.
 Array: A collection of elements of the same type stored in contiguous memory locations (e.g., int
arr[5];).
 Pointer: Stores the memory address of another variable (e.g., int *ptr;).
 Reference: An alias for another variable (e.g., int &ref = var;).

3. User Defined Data Types

These allow the programmer to define their own data types. They include:

 Class: A blueprint for creating objects that encapsulate data and functions.
 Structure (struct): A group of variables of different data types under a single name.
 Union: Similar to a structure, but all members share the same memory location, so only one
member can hold a value at a time.
 Enum: A user-defined type consisting of integral constants (e.g., enum Color {RED, GREEN,
BLUE};).
 Typedef: Used to give a new name to an existing data type (e.g., typedef unsigned long int uli;).

Q 18. Write a C++ program that inputs a String from the keyboard and Determines
the length of String.
Solution:

#include <iostream>

using namespace std;

int main() {

char userInput[100];

cout << "Enter a string: ";


cin.getline(userInput, 100);

int length = 0;

while (userInput[length] != '\0') {


length++;
}

cout << "The length of the string is: " << length << endl;

return 0;
}
Q 19. Write a simple C++ program to manipulate a stack where push and pop functions are used to
help this manipulation.

Solution:

#include <iostream>
#include <stack>
using namespace std;

int main() {
stack<int> myStack;

// Pushing elements onto the stack


myStack.push(10);
myStack.push(20);
myStack.push(30);

cout << "Elements pushed onto the stack: 10, 20, 30" << endl;

// Popping elements from the stack


cout << "Popping elements from the stack:" << endl;

while (!myStack.empty()) {
cout << myStack.top() << endl;
myStack.pop();
}

return 0;
}

Q 20. Write a C++ program to evaluate the following function:


Sum= 1+(1/2)2+(1/3)2+(1/4)2+…….

Solution:

#include <iostream>
#include <cmath> // For pow() function

using namespace std;

int main() {

int n; // Number of terms


double sum = 0.0;

cout << "Enter the number of terms: ";


cin >> n;

for (int i = 1; i <= n; ++i)


{
sum += 1.0 / pow(i, 2); // Add (1/i^2) to sum
}
cout << "Sum = " << sum << endl;

return 0;
}

Q 21. “Encapsulation Reduces the Complexity” - Justify your position.

Encapsulation reduces complexity in a simple way:

1. Hides Details: It keeps the internal workings of an object hidden from the outside world. This means
you only need to know how to use an object, not how it works internally.

2. Organizes Code: It groups related data and functions into a single unit (a class). This makes the code
easier to manage and understand.

3. Easier Changes: If you need to change how something works, you only need to update the code inside
the class. The rest of your program remains unaffected.

4. Prevents Errors: By controlling access to the data (usually through methods), it helps prevent
accidental changes to the object's state from outside the class.

therefore, encapsulation simplifies program by hiding complexity, organizing code better, making
updates easier, and reducing errors.

Q 22. Define the following terms-

i) Object ii) Class iii) Inheritance


iv) Data abstraction and Data encapsulation v) Polymorphism
vi) Dynamic binding vii) Message passing

Object: In OOP object is the representation of real life entity. Objects are instances of classes. Each
object contains data and functions to manipulate the data. Following statements declare two objects of
class Box −

Box Box1; // Declare Box1 of type Box


Box Box2; // Declare Box2 of type Box

Both of the objects Box1 and Box2 will have their own copy of data members.

Class: Class is the blue print for creating object. Objects are variables of the type class. Once a class has
been defined, we can create any number of objects belonging to that class. A class definition starts with
the keyword class followed by the class name; and the class body, enclosed by a pair of curly braces. A
class definition must be followed either by a semicolon or a list of declarations. For example, we defined
the Box data type using the keyword class as follows –

class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

Inheritance: It is the process by which object of one class acquire the properties or features of objects of
another class. The concept of inheritance provides the idea of re-usability. Means we can add additional
features to an existing class without modifying it.

Syntax:
class subclass_name : access_mode base_class_name
{
//body of subclass
};

Data abstraction and Encapsulation: Data abstraction refers to, providing only essential information to
the outside world and hiding their background details, i.e., to represent the needed information in
program without presenting the details. Encapsulation is an Object Oriented Programming concept that
binds together the data and functions in single unit and that keeps both safe from outside interference and
misuse.

Polymorphism: The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of an object to take on many forms.
Real life example of polymorphism, a person at the same time can have different characteristic. Like a
man at the same time is a father, a husband, an employee. So the same person possess different behavior
in different situations. This is called polymorphism. Polymorphism is considered as one of the important
features of Object Oriented Programming.

Dynamic binding: Dynamic binding also called dynamic dispatch is the process of linking
procedure call to a specific sequence of code (method) at run-time. It means that the code
to be executed for a specific procedure call is not known until run-time. Dynamic binding
is also known as late binding or run-time binding.
Message Passing: In Object-Oriented Programming (OOP), message passing is a way for objects to
communicate with each other by sending messages. A message is a request sent by one object to another
object to perform a certain action or to return some information.
When an object receives a message, it decides how to respond based on its own internal state and the
content of the message. This is known as message handling or message processing.

Q. Difference between data abstraction and data encapsulation.

DATA ABSTRACTION DATA ENCAPSULATION

It shows, what elements are necessary to build a It hides the complexity of a system.
system.

Its application during 'design level'. Its application during 'Implementation level'.

Abstraction Focus is on "what" should be done Encapsulation Focus is on "how" it should be


done.

This is Achieved through encapsulation. This is Achieved through making the members of a
class as 'private'.

The GUI of a mobile phone, it has some icons to After the icon is clicked, the end user has no idea
click on, which on click perform the specific regarding its implementation details
function.

You might also like