Week 11 - OOP concepts & LLMs

Object oriented programming

Classes and objects

Encapsulation

Code style: clean code

LLMs

Tokenization

Inference

Tools

RAGs

Using LLMs in Code

Practice

Assignment

Back to core program

Encapsulation

Encapsulation is one of the main principles of Object-Oriented Programming. It means bundling data (properties) and the methods that work on that data together inside a class, and controlling how that data is accessed or modified.

In simple words, encapsulation keeps related information and behavior in one place and protects it from being changed incorrectly.

When we create a class, we are already practicing encapsulation. The class groups properties and methods that belong together. For example, a bank account has a balance (data) and actions like deposit and withdraw (methods). These are bundled inside one class.

Here is a simple example:

class BankAccount {
  constructor(owner, balance) {
    this.owner = owner; // property
    this.balance = balance; // property
  }

  deposit(amount) {
    // method
    this.balance += amount;
  }

  withdraw(amount) {
    // method
    this.balance -= amount;
  }
}

In this example, the data (owner, balance) and the methods (deposit, withdraw) are bundled together inside the BankAccount class. This is the first part of encapsulation, grouping related data and behavior into one unit.

However, there is another important part of encapsulation: protecting the data. If balance is public, anyone can change it directly:

let account = new BankAccount("Riya", 1000);
account.balance = -5000; // This should not be allowed!

This can lead to incorrect or unsafe data.

To improve protection, we can make the property private using the # symbol:

class BankAccount {
  #balance;

  constructor(owner, balance) {
    this.owner = owner;
    this.#balance = balance;
  }

  deposit(amount) {
    if (amount > 0) {
      this.#balance += amount;
    }
  }

  getBalance() {
    returnthis.#balance;
  }
}

Now, #balance cannot be accessed directly from outside the class. The only way to change or see the balance is through controlled methods like deposit() or getBalance().

This is full encapsulation:

Encapsulation makes programs safer, more organized, and easier to maintain. It ensures that objects manage their own data properly instead of allowing other parts of the program to change it freely.


The HackYourFuture curriculum is licensed under CC BY-NC-SA 4.0

CC BY-NC-SA 4.0 Icons

*https://hackyourfuture.net/*

Found a mistake or have a suggestion? Let us know in the feedback form.