OOP Notes
Understand instance variables, class variables, instance methods, static methods, and how attributes and methods define an object
// Two objects — independent attribute values Smartphone phone1 = new Smartphone("Apple", "iPhone 15", 256000); Smartphone phone2 = new Smartphone("Samsung", "Galaxy S24", 128000); // phone1.batteryPercent and phone2.batteryPercent are completely independent
## Class Variables (Static Attributes)
Class variables are shared across ALL objects of a class. There's only one copy, regardless of how many objects exist.class Employee: # Class variable — shared by ALL employees company_name = "TechCorp" total_employees = 0
def __init__(self, name, role, salary): # Instance variables — unique to each employee self.name = name self.role = role self.salary = salary self.employee_id = Employee.total_employees + 1 Employee.total_employees += 1 # Updates the shared count
def __str__(self): return f"{self.name} ({self.role}) at {Employee.company_name}"
alice = Employee("Alice", "Engineer", 95000) bob = Employee("Bob", "Designer", 85000)
print(Employee.total_employees) # 2 — shared across all instances print(alice.company_name) # "TechCorp" — accessed via instance too print(bob.employee_id) # 2 — unique to Bob
public class Playlist { private String name; private List<String> songs; private int currentIndex;
public Playlist(String name) { this.name = name; this.songs = new ArrayList<>(); this.currentIndex = 0; }
// Method that modifies state public void addSong(String song) { songs.add(song); System.out.println("Added: " + song); }
// Method that reads state public String getCurrentSong() { if (songs.isEmpty()) return "No songs in playlist"; return songs.get(currentIndex); }
// Method that modifies state with logic public String next() { if (songs.isEmpty()) return "Playlist is empty"; currentIndex = (currentIndex + 1) % songs.size(); return getCurrentSong(); }
public String previous() { if (songs.isEmpty()) return "Playlist is empty"; currentIndex = (currentIndex - 1 + songs.size()) % songs.size(); return getCurrentSong(); }
// Method that returns computed value public int getLength() { return songs.size(); } }
## Types of Methods
### Accessor Methods (Getters)
Read and return attribute values without modifying them:public String getName() { return name; } public double getBalance() { return balance; }
public void setAge(int age) { if (age < 0 || age > 150) { throw new IllegalArgumentException("Invalid age"); } this.age = age; }
class Circle: def __init__(self, radius): self.radius = radius
def area(self): return 3.14159 * self.radius ** 2
def circumference(self): return 2 * 3.14159 * self.radius
def is_larger_than(self, other): """Compares this circle with another""" return self.area() > other.area()
### Static Methods
Belong to the class, not any specific object:public class MathUtils { // Static method — no object needed public static double celsiusToFahrenheit(double celsius) { return celsius * 9.0 / 5.0 + 32; }
public static int factorial(int n) { if (n <= 1) return 1; return n * factorial(n - 1); } }
// Called on the class, not an object double temp = MathUtils.celsiusToFahrenheit(100); // 212.0 int fact = MathUtils.factorial(5); // 120
#include <iostream> #include <string> #include <vector>
class Library { private: std::string name; // Instance attribute std::vector<std::string> books; // Instance attribute static int totalLibraries; // Class attribute
public: Library(const std::string& name) : name(name) { totalLibraries++; }
// Instance method void addBook(const std::string& book) { books.push_back(book); }
// Const method — promises not to modify the object int getBookCount() const { return books.size(); }
// Static method — belongs to class static int getTotalLibraries() { return totalLibraries; }
void displayInfo() const { std::cout << name << " has " << books.size() << " books" << std::endl; } };
int Library::totalLibraries = 0; // Initialize static member
int main() { Library city("City Library"); Library school("School Library");
city.addBook("Clean Code"); city.addBook("Design Patterns"); school.addBook("Algorithms");
city.displayInfo(); // City Library has 2 books school.displayInfo(); // School Library has 1 books std::cout << "Total: " << Library::getTotalLibraries() << std::endl; // 2 }
## Method Parameters and Return Values
Methods can accept parameters and return values, just like regular functions:class TemperatureConverter: def __init__(self, base_temp, scale="celsius"): self.temperature = base_temp self.scale = scale
def convert_to(self, target_scale): """Returns converted temperature without modifying the object""" if self.scale == target_scale: return self.temperature
if self.scale == "celsius" and target_scale == "fahrenheit": return self.temperature * 9/5 + 32 elif self.scale == "fahrenheit" and target_scale == "celsius": return (self.temperature - 32) * 5/9 elif self.scale == "celsius" and target_scale == "kelvin": return self.temperature + 273.15
def adjust(self, delta): """Modifies the object's state""" self.temperature += delta return self # Enables method chaining
Method chaining
temp = TemperatureConverter(20, "celsius") temp.adjust(5).adjust(3) # Now 28°C print(temp.convert_to("fahrenheit")) # 82.4
## Common Mistakes
1. **Putting unrelated attributes in a class** — each class should have a cohesive set of attributes
2. **Methods that don't use `self`/`this`** — if a method doesn't need object state, make it static
3. **Too many public attributes** — prefer private attributes with controlled access
4. **Methods doing too many things** — each method should have a single, clear purpose
5. **Forgetting `self` parameter in Python** — first parameter of instance methods must be `self`
## Key Takeaways
- **Attributes** store an object's state; **methods** define its behavior
- **Instance attributes** are unique per object; **class/static attributes** are shared
- Methods should be cohesive — related to the class's purpose
- Use **getters/setters** for controlled attribute access
- **Static methods** don't need an object instance and belong to the class itself
- Good design means each class has attributes and methods that logically belong togetherExam Focus
Revise definitions, diagrams, examples, and short-answer points for Attributes and Methods.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Object Oriented Programming (OOP) topic.
Search Terms
object-oriented-programming, object oriented programming (oop), object, oriented, programming, oop, basics, attributes
Related Object Oriented Programming (OOP) Topics