Computer ScienceUnit 610 min read
Object-Oriented Programming: Classes, Objects, Inheritance & Polymorphism
Unit 6 of Computer Science teaches how to design programs using objects, classes, inheritance, and polymorphism—key concepts that make code reusable, modular, and easier to maintain. Learn with real-world examples, diagrams, and NEB-style questions.
TAKEAWAYS:
- Objects and classes are the building blocks of OOP, where a class is a blueprint and an object is an instance of that blueprint.
- Inheritance allows a new class (child) to reuse and extend properties/methods of an existing class (parent), saving time and reducing errors.
- Polymorphism lets one method name behave differently based on the object calling it (e.g.,
draw()forCirclevs.Rectangle). - Encapsulation hides data and exposes only necessary methods, improving security and control.
- OOP improves code reusability, scalability, and maintainability compared to procedural programming.
- NEB exams test conceptual understanding, code snippets, and real-world applications of OOP.
1. Introduction to Object-Oriented Programming (OOP)
OOP is a programming paradigm that organizes software design around objects (real-world entities) rather than functions and logic. It mimics how we think in the real world, making programs easier to understand and modify.
Why OOP?
- Modularity: Code is divided into objects, making it easier to manage.
- Reusability: Objects can be reused in different programs.
- Scalability: Large programs become easier to extend.
- Security: Data is hidden (encapsulation), reducing errors.
Key Concepts of OOP
2. Classes and Objects
Class: A Blueprint
A class defines the attributes (data) and methods (functions) that objects of that class will have.
Example: A Car class might have attributes like color, model, and methods like start(), stop().
Object: An Instance of a Class
An object is a real entity created from a class.
Example: myCar = Car() creates an object of the Car class.
Syntax in C++ (Example)
#include <iostream>
using namespace std;
class Car { // Class definition
public:
string color; // Attribute
string model; // Attribute
void start() { // Method
cout << "Car started!" << endl;
}
};
int main() {
Car myCar; // Object creation
myCar.color = "Red";
myCar.model = "Toyota";
myCar.start(); // Calling method
return 0;
}
Output:
Car started!
Visualization: Class vs. Object
```figure
{"type":"layers","layers":["Class (Blueprint)","Object (Instance)","Memory Allocation"],"right":["Car (class)","myCar (object)","Heap memory"],"arrow":"From blueprint to concrete instance","caption":"How classes create objects in memory (C++ example)"}
3. The Four Pillars of OOP
(1) Encapsulation
- Definition: Bundling data (attributes) and methods (functions) into a single unit (class) while hiding internal details.
- Why? Prevents unauthorized access and modifies data safely.
- How? Use access specifiers like
private,public, andprotected.
Example:
class BankAccount {
private: // Hidden from outside
double balance;
public:
void deposit(double amount) {
balance += amount;
}
void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
}
}
};
(2) Inheritance
- Definition: A mechanism where a child class inherits properties and methods from a parent class.
- Types of Inheritance:
Example (Single Inheritance):
class Animal { // Parent class
public:
void eat() {
cout << "Eating..." << endl;
}
};
class Dog : public Animal { // Child class
public:
void bark() {
cout << "Barking..." << endl;
}
};
int main() {
Dog myDog;
myDog.eat(); // Inherited from Animal
myDog.bark(); // Own method
return 0;
}
Output:
Eating...
Barking...
(3) Polymorphism
- Definition: The ability of an object to take many forms.
- Types:
- Compile-time (Method Overloading): Same method name, different parameters.
- Run-time (Method Overriding): Child class redefines a parent class method.
Example (Method Overriding):
class Shape {
public:
virtual void draw() { // Virtual function
cout << "Drawing a shape" << endl;
}
};
class Circle : public Shape {
public:
void draw() { // Overriding
cout << "Drawing a circle" << endl;
}
};
int main() {
Shape *shape = new Circle();
shape->draw(); // Calls Circle's draw()
delete shape;
return 0;
}
Output:
Drawing a circle
(4) Abstraction
- Definition: Hiding complex implementation details and showing only essential features.
- How? Using abstract classes and interfaces.
- Example:
class Vehicle { // Abstract class public: virtual void move() = 0; // Pure virtual function };
class Car : public Vehicle { public: void move() { cout << "Car is moving" << endl; } };
---
### **4. Comparison: OOP vs. Procedural Programming**
| Feature | OOP | Procedural Programming |
|-----------------------|------------------------------|----------------------------------|
| **Approach** | Objects and classes | Functions and procedures |
| **Code Reusability** | High (inheritance) | Low |
| **Modularity** | High (objects are modular) | Low (functions are scattered) |
| **Maintainability** | Easy (changes in one place) | Hard (changes affect many places)|
| **Real-world Modeling**| Natural (objects mimic reality)| Less natural |
---
### **5. Advantages and Disadvantages of OOP**
#### **Advantages**
✅ **Reusability**: Inheritance allows code reuse.
✅ **Modularity**: Objects can be developed independently.
✅ **Scalability**: Easy to add new features.
✅ **Security**: Encapsulation protects data.
✅ **Maintainability**: Changes are localized.
#### **Disadvantages**
❌ **Complexity**: More complex than procedural programming.
❌ **Performance Overhead**: Slightly slower due to abstraction.
❌ **Design Time**: Requires careful planning.
---
### **6. Real-World Applications of OOP**
- **GUI Development** (e.g., buttons, text fields in Java Swing).
- **Game Development** (e.g., characters, weapons in Unity).
- **Database Systems** (e.g., ORM tools like Hibernate).
- **Operating Systems** (e.g., file handling in Windows/Linux).
---
### **7. Solved Examples**
#### **Example 1: Class and Object**
```cpp
#include <iostream>
using namespace std;
class Student {
public:
string name;
int rollNo;
void display() {
cout << "Name: " << name << ", Roll No: " << rollNo << endl;
}
};
int main() {
Student s1;
s1.name = "Ramesh";
s1.rollNo = 101;
s1.display();
return 0;
}
Output:
Name: Ramesh, Roll No: 101
Example 2: Inheritance
class Animal {
public:
void eat() {
cout << "Eating..." << endl;
}
};
class Dog : public Animal {
public:
void bark() {
cout << "Barking..." << endl;
}
};
int main() {
Dog d;
d.eat(); // Inherited
d.bark(); // Own method
return 0;
}
Output:
Eating...
Barking...
8. NEB Board-Style Questions
Short Answer Questions
Define class and object with an example.
- Answer: A class is a blueprint (e.g.,
Car), and an object is an instance (e.g.,myCar = Car()).
- Answer: A class is a blueprint (e.g.,
What is inheritance? Explain with a diagram.
- Answer:
classDiagram Animal <|-- Dog Animal <|-- Cat Dog -->|"Inherits"| Animal
- Answer:
Differentiate between method overloading and overriding.
- Answer:
Feature Overloading Overriding Definition Same name, different params Same name, same params Time Compile-time Run-time Inheritance Same class Child overrides parent
- Answer:
Programming Questions
Write a C++ program to create a class
Rectanglewith attributeslengthandwidth. Include methods to calculatearea()andperimeter().#include <iostream> using namespace std; class Rectangle { private: int length, width; public: void setValues(int l, int w) { length = l; width = w; } int area() { return length * width; } int perimeter() { return 2 * (length + width); } }; int main() { Rectangle r; r.setValues(5, 3); cout << "Area: " << r.area() << endl; cout << "Perimeter: " << r.perimeter() << endl; return 0; }Output:
Area: 15 Perimeter: 16Explain polymorphism with an example of method overriding.
- Answer: See Example 2 above (Circle overriding Shape’s
draw()).
- Answer: See Example 2 above (Circle overriding Shape’s
Exam Tip
✅ NEB often tests:
- Definitions of class, object, inheritance, polymorphism.
- Code snippets (write small programs on demand).
- Diagrams (UML class diagrams, inheritance trees).
- Advantages/disadvantages of OOP.
- Real-world applications (e.g., "How is OOP used in game development?").
🔹 Avoid memorizing syntax—focus on concepts and logic.
🔹 Practice writing small programs (e.g., Student, BankAccount).
🔹 Draw diagrams for inheritance and polymorphism questions.
Good luck! 🚀 Keep practicing OOP concepts with real-world examples.
Based on the NEB +2 Management syllabus for Computer Science (Comp), unit 6.
Discussion
Loading…