Chapter 6: Object-Oriented Programming (OOP)

Learn classes, objects, attributes, methods, constructors, inheritance, encapsulation, polymorphism and abstraction for application development.

ClassesObjectsInheritanceEncapsulationPolymorphismAbstraction
Design
Classes
Create
Objects
Reuse
Code
Build
Apps

6.1 Chapter Overview

Object-Oriented Programming, or OOP, is a programming approach that organizes software around objects. An object represents a real-world entity such as a student, employee, product, bank account, course or vehicle.

OOP helps developers build applications that are easier to maintain, reuse, expand and understand. It is widely used in C++, Java, Python, C#, PHP and many modern application development environments.

Learning Outcome: Apply object-oriented concepts in application development using classes, objects, attributes, methods, constructors, inheritance, encapsulation, polymorphism and abstraction.

6.2 OOP Concepts at a Glance

ConceptMeaningExample
ClassBlueprint or template for creating objects.Student class
ObjectActual instance created from a class.student1, student2
AttributeData stored inside an object.name, marks, age
MethodFunction or behavior inside a class.displayResult()
ConstructorSpecial method used to initialize an object.Student("Amin", 85)
InheritanceOne class receives properties from another class.Employee inherits Person
EncapsulationProtecting data inside a class.private balance
PolymorphismSame method name behaves differently.calculateSalary()
AbstractionShowing essential features and hiding details.Payment interface

6.3 Classes and Objects

A class is a blueprint. An object is a real item created from that blueprint. For example, Student can be a class, while Amin and Siti can be objects.

Working Example: Student Class and Object

C++
#include <iostream>
using namespace std;

class Student {
public:
    string name;
    int marks;

    void display() {
        cout << "Name: " << name << endl;
        cout << "Marks: " << marks;
    }
};

int main() {
    Student s1;
    s1.name = "Amin";
    s1.marks = 85;
    s1.display();
    return 0;
}
Java
class Student {
    String name;
    int marks;

    void display() {
        System.out.println("Name: " + name);
        System.out.println("Marks: " + marks);
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student();
        s1.name = "Amin";
        s1.marks = 85;
        s1.display();
    }
}
Python
class Student:
    def display(self):
        print("Name:", self.name)
        print("Marks:", self.marks)

s1 = Student()
s1.name = "Amin"
s1.marks = 85
s1.display()
Expected Output:
Name: Amin
Marks: 85
Note: C is not an object-oriented language in the same way as C++, Java and Python. OOP is usually taught with C++, Java and Python.

Online Working Example

Select language and click Run.

6.4 Attributes and Methods

Attributes store data inside an object. Methods define what an object can do. For example, a BankAccount object may have balance as an attribute and deposit() as a method.

Working Example: Bank Account

C++
class BankAccount {
public:
    double balance;

    void deposit(double amount) {
        balance = balance + amount;
    }

    void showBalance() {
        cout << "Balance: RM " << balance;
    }
};
Java
class BankAccount {
    double balance;

    void deposit(double amount) {
        balance = balance + amount;
    }

    void showBalance() {
        System.out.println("Balance: RM " + balance);
    }
}
Python
class BankAccount:
    def deposit(self, amount):
        self.balance = self.balance + amount

    def show_balance(self):
        print("Balance: RM", self.balance)

Online Working Example

Select language and click Run.

6.5 Constructors

A constructor is a special method that runs automatically when an object is created. It is commonly used to initialize object attributes.

Working Example: Course Constructor

C++
class Course {
public:
    string title;
    int duration;

    Course(string t, int d) {
        title = t;
        duration = d;
    }

    void display() {
        cout << title << " - " << duration << " days";
    }
};
Java
class Course {
    String title;
    int duration;

    Course(String t, int d) {
        title = t;
        duration = d;
    }

    void display() {
        System.out.println(title + " - " + duration + " days");
    }
}
Python
class Course:
    def __init__(self, title, duration):
        self.title = title
        self.duration = duration

    def display(self):
        print(self.title, "-", self.duration, "days")

Online Working Example

Select language and click Run.

6.6 Inheritance

Inheritance allows one class to reuse attributes and methods from another class. The existing class is called the parent/base class, and the new class is called the child/derived class.

Working Example: Person and Trainer

C++
class Person {
public:
    string name;
};

class Trainer : public Person {
public:
    string subject;

    void display() {
        cout << name << " teaches " << subject;
    }
};
Java
class Person {
    String name;
}

class Trainer extends Person {
    String subject;

    void display() {
        System.out.println(name + " teaches " + subject);
    }
}
Python
class Person:
    def __init__(self, name):
        self.name = name

class Trainer(Person):
    def __init__(self, name, subject):
        super().__init__(name)
        self.subject = subject

    def display(self):
        print(self.name, "teaches", self.subject)

Online Working Example

Select language and click Run.

6.7 Encapsulation

Encapsulation means protecting data by keeping it inside a class and controlling access through methods. This prevents direct unsafe modification of important data.

Working Example: Protected Balance

C++
class Account {
private:
    double balance;

public:
    Account(double b) {
        balance = b;
    }

    double getBalance() {
        return balance;
    }
};
Java
class Account {
    private double balance;

    Account(double b) {
        balance = b;
    }

    public double getBalance() {
        return balance;
    }
}
Python
class Account:
    def __init__(self, balance):
        self.__balance = balance

    def get_balance(self):
        return self.__balance

Online Working Example

Select language and click Run.

6.8 Polymorphism

Polymorphism means β€œmany forms.” It allows the same method name to behave differently depending on the object or class.

Working Example: Different Payment Types

C++
class Payment {
public:
    virtual void pay() {
        cout << "General payment";
    }
};

class CardPayment : public Payment {
public:
    void pay() override {
        cout << "Paid by card";
    }
};
Java
class Payment {
    void pay() {
        System.out.println("General payment");
    }
}

class CardPayment extends Payment {
    void pay() {
        System.out.println("Paid by card");
    }
}
Python
class Payment:
    def pay(self):
        print("General payment")

class CardPayment(Payment):
    def pay(self):
        print("Paid by card")

Online Working Example

Select language and click Run.

6.9 Abstraction

Abstraction means showing only essential features and hiding unnecessary details. In application development, abstraction helps developers focus on what an object does, not how it does it internally.

Working Example: Shape Area

C++
class Shape {
public:
    virtual double area() = 0;
};

class Rectangle : public Shape {
public:
    double length, width;
    double area() override {
        return length * width;
    }
};
Java
abstract class Shape {
    abstract double area();
}

class Rectangle extends Shape {
    double length, width;

    double area() {
        return length * width;
    }
}
Python
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

class Rectangle(Shape):
    def __init__(self, length, width):
        self.length = length
        self.width = width

    def area(self):
        return self.length * self.width

Online Working Example

Select language and click Run.

6.10 OOP Application Example

A student result system can be designed using OOP by creating a Student class with attributes and methods.

Online Working Example: Student Result Class

Select language and click Run.

6.11 Practical Activities

Activity 1: Student Class

Create a Student class with name, marks and display method.

Activity 2: Bank Account

Create a BankAccount class with balance, deposit and show balance methods.

Activity 3: Inheritance

Create a Person parent class and Trainer child class.

Activity 4: Encapsulation

Create a class with private balance and public getter method.

Mini Project

Build an OOP Student Result System using class, object, constructor, attributes and methods.

6.12 Interactive Final Assessment Quiz

Each correct answer gives +1 mark. Each wrong answer gives -0.5 mark. Correct answers are mixed.

1. A class is a blueprint for creating objects.

2. Which OOP concept allows one class to reuse another class?

3. Attributes represent data stored inside an object.

4. A constructor is usually used to initialize an object.

5. Encapsulation means:

6. Polymorphism means the same method name can behave differently.

7. Abstraction hides unnecessary implementation details.

8. Which Python method is commonly used as a constructor?

9. An object is an instance of a class.

10. OOP cannot be used in application development.

Your Score: 0

6.13 Chapter Summary

This chapter introduced Object-Oriented Programming concepts including classes, objects, attributes, methods, constructors, inheritance, encapsulation, polymorphism and abstraction.

Remember: OOP helps developers build organized, reusable and scalable applications by modeling real-world entities as objects.