Comp Computer Science

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:

  1. Encapsulation
  2. Inheritance
  3. Polymorphism
  4. 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 : creates

Key Points:

  • A class is like a cookie cutter; objects are the cookies.
  • Objects have state (data) and behavior (methods).
  • private members are hidden; public members 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:

Public InterfaceMethods (deposit, withdraw)Private Databalance (hidden)
Encapsulation hides data (balance) and exposes only controlled methods.

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/private inheritance: 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:

  1. 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; }
      };
      
  2. 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):

draw() → 'Drawing a circle'Circledraw() → 'Drawing a rectangle'RectangleShape
Polymorphism: Same method (draw()) behaves differently per class.

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

  1. Define:

    • Class
    • Object
    • Inheritance
    • Polymorphism
  2. Differentiate between:

    • Encapsulation and abstraction.
    • Compile-time and runtime polymorphism.
  3. 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

  1. Explain the four pillars of OOP with examples. (5 marks)
  2. Write a C++ program to create a class BankAccount with private members accountNo and balance. Use encapsulation to provide public methods deposit() and withdraw(). Derive a class SavingsAccount that adds a method addInterest(). Demonstrate polymorphism by overriding a display() method. (10 marks)

Exam Tips

  1. Understand Concepts First:

    • NEB exams test conceptual clarity. Know the difference between OOP and procedural programming, inheritance types, and polymorphism kinds.
  2. Practice Coding:

    • Write programs for:
      • Class and object creation.
      • Inheritance (single, multilevel).
      • Method overriding and overloading.
      • Abstract classes.
  3. Diagrams Matter:

    • Draw class diagrams (e.g., inheritance hierarchies) to visualize relationships.
  4. Common Mistakes to Avoid:

    • Forgetting virtual keyword for runtime polymorphism.
    • Misusing access modifiers (private vs. public).
    • Not initializing objects properly.
  5. 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…