Computer ScienceUnit 612 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 examples, diagrams, and NEB-style questions.
TAKEAWAYS:
- Objects and classes are the building blocks of OOP, where a class is a blueprint and objects are instances of that blueprint.
- Inheritance allows a class (child) to reuse and extend properties/methods from another class (parent), promoting code reuse.
- Polymorphism lets one interface (e.g., a function) work with different data types, improving flexibility.
- Encapsulation hides data and exposes only necessary methods, ensuring controlled access to object attributes.
- OOP principles like abstraction simplify complex systems by focusing on essential features.
- NEB exams test conceptual understanding (e.g., differences between OOP and procedural programming) and coding (e.g., writing class definitions).
What is Object-Oriented Programming (OOP)?
Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around objects (real-world entities like a Student, BankAccount, or Car) rather than functions and logic. Unlike procedural programming (which focuses on writing procedures or functions), OOP bundles data (attributes) and behavior (methods) into a single unit called a class.
Why Use OOP?
OOP makes programs:
- Modular: Code is divided into reusable objects.
- Scalable: Easy to add new features without breaking existing code.
- Maintainable: Clear structure reduces errors.
- Reusable: Classes can be inherited and extended.
Core Concepts of OOP
OOP is built on four pillars:
- Encapsulation
- Inheritance
- Polymorphism
- Abstraction
Let’s explore each with examples and diagrams.
1. Class and Object
A class is a blueprint (template) that defines attributes (data) and methods (functions). An object is an instance of a class.
Example:
// Class definition (blueprint)
class Student {
private: // Encapsulation: data is hidden
char name[50];
int rollNo;
public: // Methods to interact with data
void setData(char n[], int r) {
strcpy(name, n);
rollNo = r;
}
void display() {
printf("Name: %s, Roll: %d\n", name, rollNo);
}
};
// Creating objects (instances)
Student s1, s2; // Two objects of class Student
s1.setData("Ramesh", 101);
s2.setData("Sita", 102);
s1.display(); // Output: Name: Ramesh, Roll: 101
Visualization:
classDiagram
class Student {
-name: char[50]
-rollNo: int
+setData(char[], int)
+display()
}
Student --> "1" s1 : creates
Student --> "1" s2 : createsKey Points:
- A class is like a cookie cutter; objects are the cookies.
- Objects have state (data) and behavior (methods).
privatemembers are hidden;publicmembers are accessible.
2. Encapsulation
Encapsulation is the mechanism of bundling data and methods that operate on the data within a single unit (class) while restricting direct access to some components.
How?
- Use access modifiers:
private: Accessible only within the class.public: Accessible from anywhere.protected: Accessible within the class and derived classes (inheritance).
Example:
class BankAccount {
private:
double balance;
public:
void deposit(double amount) {
if (amount > 0) balance += amount;
}
void withdraw(double amount) {
if (amount <= balance) balance -= amount;
}
double getBalance() { return balance; } // Controlled access
};
Why?
- Prevents invalid operations (e.g., withdrawing more than the balance).
- Protects data integrity.
Visualization:
3. Inheritance
Inheritance allows a child class (derived class) to inherit properties and methods from a parent class (base class). This promotes code reuse.
Types of Inheritance:
| Type | Description | Example |
|---|---|---|
| Single | One child inherits from one parent. | class Car : public Vehicle |
| Multilevel | Grandchild inherits from child, which inherits from parent. | A → B → C |
| Hierarchical | Multiple children inherit from one parent. | Parent → Child1, Child2 |
| Multiple | One child inherits from two parents (C++ supports this; Java does not). | class Hybrid : public A, B |
| Hybrid | Combination of two or more types. | Complex scenarios. |
Example (Single Inheritance):
class Animal { // Parent class
public:
void eat() { printf("Eating...\n"); }
};
class Dog : public Animal { // Child class
public:
void bark() { printf("Barking...\n"); }
};
int main() {
Dog d;
d.eat(); // Inherited from Animal
d.bark(); // Own method
return 0;
}
Output:
Eating...
Barking...
Visualization:
classDiagram
class Animal {
+eat()
}
class Dog {
+bark()
}
class Cat {
+meow()
}
Dog -->|Inherits| Animal
Cat -->|Inherits| Animal
note for Animal "Base class\nCommon behavior"
note for Dog "Subclass\nSpecialized behavior"Key Points:
- Reuse code: Avoid rewriting the same logic.
- Extensibility: Add new features to existing classes.
public/privateinheritance: Affects access to parent members.
4. Polymorphism
Polymorphism means "many forms". It allows one interface (e.g., a function or operator) to work with different data types.
Types:
Compile-time (Static) Polymorphism:
- Achieved via function overloading (same name, different parameters).
- Example:
class Math { public: int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } };
Run-time (Dynamic) Polymorphism:
- Achieved via function overriding (child class redefines parent method) and virtual functions.
- Example:
class Shape { public: virtual void draw() { printf("Drawing a shape\n"); } }; class Circle : public Shape { public: void draw() { printf("Drawing a circle\n"); } // Overrides parent };
Visualization (Function Overriding):
Key Points:
- Flexibility: Write generic code that works with multiple types.
- Extensibility: Add new subclasses without modifying existing code.
5. Abstraction
Abstraction hides complexity and shows only essential features. It is achieved using:
- Abstract classes (classes with at least one pure virtual function).
- Interfaces (100% abstract classes in some languages like Java).
Example (Abstract Class in C++):
class Vehicle { // Abstract class
public:
virtual void start() = 0; // Pure virtual function
void stop() { printf("Stopping...\n"); }
};
class Car : public Vehicle {
public:
void start() { printf("Car starts with a key\n"); }
};
int main() {
Car c;
c.start(); // Output: Car starts with a key
c.stop(); // Output: Stopping...
return 0;
}
Key Points:
- Focus on "what" not "how": Users interact with simplified interfaces.
- Security: Hide implementation details.
OOP vs. Procedural Programming
| Feature | OOP | Procedural Programming |
|---|---|---|
| Focus | Objects and data | Functions and logic |
| Code Organization | Modular (classes/objects) | Linear (procedures) |
| Reusability | High (inheritance) | Low (copy-paste code) |
| Maintainability | Easy (encapsulation) | Hard (global variables) |
| Example | class Student { ... } |
void calculateGrade() { ... } |
NEB-Style Solved Examples
Example 1: Class and Object
Question: Define a class Rectangle with attributes length and width. Write a method to calculate its area.
Solution:
class Rectangle {
private:
double length, width;
public:
void setDimensions(double l, double w) {
length = l;
width = w;
}
double area() { return length * width; }
};
int main() {
Rectangle r;
r.setDimensions(5.0, 3.0);
printf("Area: %.2f\n", r.area()); // Output: Area: 15.00
return 0;
}
Example 2: Inheritance
Question: Create a base class Person with a method display(). Derive a class Employee that inherits from Person and adds a method showSalary().
Solution:
class Person {
public:
void display() { printf("Person details\n"); }
};
class Employee : public Person {
public:
void showSalary() { printf("Salary: $5000\n"); }
};
int main() {
Employee e;
e.display(); // Inherited
e.showSalary(); // Own method
return 0;
}
Example 3: Polymorphism (Function Overriding)
Question: Write a program to demonstrate runtime polymorphism using a base class Shape and derived classes Circle and Triangle.
Solution:
class Shape {
public:
virtual void draw() { printf("Drawing a shape\n"); }
};
class Circle : public Shape {
public:
void draw() { printf("Drawing a circle\n"); }
};
class Triangle : public Shape {
public:
void draw() { printf("Drawing a triangle\n"); }
};
int main() {
Shape *s1 = new Circle();
Shape *s2 = new Triangle();
s1->draw(); // Output: Drawing a circle
s2->draw(); // Output: Drawing a triangle
return 0;
}
NEB Board-Style Questions
Short Answer Questions
Define:
- Class
- Object
- Inheritance
- Polymorphism
Differentiate between:
- Encapsulation and abstraction.
- Compile-time and runtime polymorphism.
Write the output:
class Base { public: void show() { printf("Base\n"); } }; class Derived : public Base { public: void show() { printf("Derived\n"); } }; int main() { Base *b = new Derived(); b->show(); return 0; }Answer:
Derived(runtime polymorphism).
Long Answer Questions
- Explain the four pillars of OOP with examples. (5 marks)
- Write a C++ program to create a class
BankAccountwith private membersaccountNoandbalance. Use encapsulation to provide public methodsdeposit()andwithdraw(). Derive a classSavingsAccountthat adds a methodaddInterest(). Demonstrate polymorphism by overriding adisplay()method. (10 marks)
Exam Tips
Understand Concepts First:
- NEB exams test conceptual clarity. Know the difference between OOP and procedural programming, inheritance types, and polymorphism kinds.
Practice Coding:
- Write programs for:
- Class and object creation.
- Inheritance (single, multilevel).
- Method overriding and overloading.
- Abstract classes.
- Write programs for:
Diagrams Matter:
- Draw class diagrams (e.g., inheritance hierarchies) to visualize relationships.
Common Mistakes to Avoid:
- Forgetting
virtualkeyword for runtime polymorphism. - Misusing access modifiers (
privatevs.public). - Not initializing objects properly.
- Forgetting
NEB loves:
- Short definitions (e.g., "Inheritance is the process where a class inherits properties from another class").
- Code snippets with outputs.
- Comparative tables (e.g., OOP vs. procedural).
Based on the NEB +2 Science syllabus for Computer Science (Comp), unit 6.
Discussion
Loading…