OOP Notes
Master the this keyword — how it references the current object, resolves naming conflicts, enables method chaining, and passes the current object to other methods.
public class Rectangle { private double width; private double height;
public Rectangle(double width, double height) { this.width = width; // 'this.width' is the field this.height = height; // 'height' alone is the parameter }
public void resize(double width, double height) { this.width = width; this.height = height; } }
public class QueryBuilder { private String table; private String whereClause; private String orderBy; private int limit;
public QueryBuilder select(String table) { this.table = table; return this; // Return current object for chaining }
public QueryBuilder where(String condition) { this.whereClause = condition; return this; }
public QueryBuilder orderBy(String column) { this.orderBy = column; return this; }
public QueryBuilder limit(int count) { this.limit = count; return this; }
public String build() { StringBuilder sql = new StringBuilder("SELECT * FROM " + table); if (whereClause != null) sql.append(" WHERE " + whereClause); if (orderBy != null) sql.append(" ORDER BY " + orderBy); if (limit > 0) sql.append(" LIMIT " + limit); return sql.toString(); } }
// Beautiful chaining thanks to 'return this' String query = new QueryBuilder() .select("users") .where("age > 18") .orderBy("name") .limit(10) .build(); // Result: "SELECT * FROM users WHERE age > 18 ORDER BY name LIMIT 10"
### 3. Constructor Chaining
`this()` calls another constructor in the same class:public class Connection { private String host; private int port; private int timeout; private boolean ssl;
// Full constructor public Connection(String host, int port, int timeout, boolean ssl) { this.host = host; this.port = port; this.timeout = timeout; this.ssl = ssl; }
// Chains to full constructor with defaults public Connection(String host, int port) { this(host, port, 30, true); // this() calls another constructor }
// Chains with more defaults public Connection(String host) { this(host, 443); // Calls the 2-parameter constructor } }
public class EventEmitter { private String name;
public EventEmitter(String name) { this.name = name; }
public void register(EventManager manager) { // Pass THIS object to be registered manager.addListener(this); } }
class TaskManager: def __init__(self, name): self.name = name self.tasks = [] self.completed = []
def add_task(self, task): self.tasks.append(task) return self # Method chaining works in Python too!
def complete_task(self, task): if task in self.tasks: self.tasks.remove(task) self.completed.append(task) return self
def status(self): print(f"\n{self.name}'s Tasks:") print(f" Pending: {len(self.tasks)}") print(f" Done: {len(self.completed)}") return self
manager = TaskManager("Alice") manager.add_task("Write report") \ .add_task("Send emails") \ .add_task("Code review") \ .complete_task("Write report") \ .status()
#include <iostream> #include <string>
class Vector2D { private: double x, y;
public: Vector2D(double x, double y) : x(x), y(y) {}
// Return reference for chaining Vector2D& add(const Vector2D& other) { this->x += other.x; this->y += other.y; return *this; // Dereference the pointer to return the object }
Vector2D& scale(double factor) { this->x *= factor; this->y *= factor; return *this; }
void print() const { std::cout << "(" << x << ", " << y << ")" << std::endl; }
// Using this to compare with another object bool equals(const Vector2D& other) const { return this->x == other.x && this->y == other.y; } };
int main() { Vector2D v(1, 2); v.add(Vector2D(3, 4)).scale(2).print(); // (8, 12) return 0; }
public class Example { private int value;
public Example(int value) { this.value = value; }
// ERROR: this() must be first statement public Example() { System.out.println("Creating..."); // Can't be before this() this(0); // COMPILE ERROR! }
// CORRECT: public Example() { this(0); // Must be first! System.out.println("Created with default value"); }
// Cannot use 'this' in static context public static void utility() { // this.value = 5; // ERROR! No 'this' in static methods } }
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for The this Keyword.
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, this
Related Object Oriented Programming (OOP) Topics