OOP Notes
Deep dive into access control mechanisms — how public, private, and protected modifiers enforce encapsulation boundaries across different languages.
class Matrix { private: double data[4][4]; int rows, cols;
public: Matrix(int r, int c) : rows(r), cols(c) { for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) data[i][j] = 0; }
void set(int r, int c, double val) { if (r >= 0 && r < rows && c >= 0 && c < cols) data[r][c] = val; }
// Friend function can access private members friend Matrix multiply(const Matrix& a, const Matrix& b); friend std::ostream& operator<<(std::ostream& os, const Matrix& m); };
// This function can access Matrix's private data directly Matrix multiply(const Matrix& a, const Matrix& b) { Matrix result(a.rows, b.cols); for (int i = 0; i < a.rows; i++) for (int j = 0; j < b.cols; j++) for (int k = 0; k < a.cols; k++) result.data[i][j] += a.data[i][k] * b.data[k][j]; return result; }
class DatabasePool: def __init__(self, max_connections=10): self.max_connections = max_connections # Public self._active_connections = [] # Protected (convention) self.__password = "secret123" # Private (name mangling) self._available = []
def get_connection(self): """Public interface""" if self._available: conn = self._available.pop() self._active_connections.append(conn) return conn if len(self._active_connections) < self.max_connections: conn = self._create_connection() self._active_connections.append(conn) return conn raise RuntimeError("Connection pool exhausted")
def release_connection(self, conn): """Public interface""" if conn in self._active_connections: self._active_connections.remove(conn) self._available.append(conn)
def _create_connection(self): """Protected: subclasses might override connection creation""" return {"id": len(self._active_connections), "active": True}
def __authenticate(self): """Private: only this class should handle auth""" return hash(self.__password)
class SSLDatabasePool(DatabasePool): def _create_connection(self): """Override protected method for SSL connections""" conn = super()._create_connection() conn["ssl"] = True return conn
## Access Control for Classes Themselves
In Java, top-level classes can only be `public` or package-private:// Public class — visible everywhere (filename must match) public class PaymentService { public void processPayment() { /* ... */ } }
// Package-private class — only visible in same package class PaymentValidator { boolean isValid(String cardNumber) { /* ... */ } }
// Inner classes can be private public class ShoppingCart { private List<CartItem> items = new ArrayList<>();
// Private inner class — only ShoppingCart can use this private class CartItem { String productId; int quantity; double price; }
public void addItem(String productId, int qty, double price) { CartItem item = new CartItem(); item.productId = productId; item.quantity = qty; item.price = price; items.add(item); } }
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Access Control in OOP.
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, encapsulation, access, control
Related Object Oriented Programming (OOP) Topics