Classes and Objects
Object-Oriented Programming (OOP) lets you model your code around real-world things (objects) rather than just sequences of actions.
Class = Blueprint, Object = Instance
A class is a blueprint that defines what data (attributes) and behaviors (methods) a type of object has. An object is a specific instance of that class.
Think of it like this: "BankAccount" is the class (the concept), while "Alice's account with $1,000" is an object (a specific account).
The Constructor
The constructor is a special method that runs when you create a new object. It sets up the initial state:
- Python:
__init__ - JavaScript:
constructor - C++/Java: A method with the same name as the class
Encapsulation
Encapsulation means bundling data and methods together and controlling access to the internals. The balance of a bank account shouldn't be changed directly — it should only change through deposit() and withdraw() methods that enforce rules.
Try It Yourself
- Add a
transfer(amount, other_account)method - Add a transaction history that logs every deposit and withdrawal
- Create a
SavingsAccountthat earns interest