Classes & Objects
Part of Object-Oriented Programming
What are Classes & Objects?
Classes are the fundamental building blocks of Object-Oriented Programming. A class is like a blueprint or template that defines the structure and behavior of objects.
Objects are instances of classes - concrete entities created from the blueprint. Each object has its own set of data (attributes) and can perform actions (methods).
Real-World Analogy
Think of a class as a cookie cutter, and objects as the cookies. The cookie cutter (class) defines the shape, but each cookie (object) can have different decorations (data). All cookies share the same basic shape, but each one is unique.
Interactive Visualization
Class & Object Visualization
Anatomy of a Class
Attributes (Properties)
- • Variables that store object data
- • Define the state of an object
- • Each instance has its own copy
- • Example: name, age, email
Methods (Functions)
- • Functions that define behavior
- • Can access and modify attributes
- • Operate on object's data
- • Example: greet(), save(), update()
Code Implementation
# Defining a class in Python
class Person:
# Constructor (initializer)
def __init__(self, name, age):
self.name = name # Instance attribute
self.age = age
# Instance method
def greet(self):
return f"Hello, I'm {self.name}!"
def celebrate_birthday(self):
self.age += 1
return f"{self.name} is now {self.age}!"
# Creating objects (instances)
alice = Person("Alice", 25)
bob = Person("Bob", 30)
# Using object methods
print(alice.greet()) # Hello, I'm Alice!
print(bob.celebrate_birthday()) # Bob is now 31!
# Accessing attributes
print(alice.name) # Alice
print(bob.age) # 31Key Concepts
Constructor
A special method called automatically when creating a new object. It initializes the object's attributes. In Python it's __init__, in Java/C++ it's the method with the same name as the class.
Instance vs Class
Instance attributes belong to each object individually. Class attributesare shared by all instances of the class. Most attributes are instance-level.
self / this
The self (Python) or this(Java, C++, JS) keyword refers to the current instance. It's how methods know which object's data to work with.
Common Mistakes
Forgetting self/this in methods
In Python, always include self as the first parameter of instance methods. Without it, you can't access instance attributes.
Confusing class with object
You can't use Person.greet() directly - you need an instance like alice.greet().
Modifying class attributes accidentally
If you define mutable default values (like lists) as class attributes, they're shared across all instances. Use instance attributes in the constructor instead.
Interview Tips
Test Your Knowledge
Classes & Objects Quiz
Question 1 of 6What is a class in OOP?