What is the "this" keyword?
Answer
The this keyword refers to the current instance of the class — the object on which the method is being called. It resolves ambiguity, enables method chaining, and can pass the current object to other methods. Uses of this: (1) Disambiguate field from parameter: class Person { private String name; private int age; public Person(String name, int age) { this.name = name; // this.name = field, name = parameter this.age = age; } }; (2) Call another constructor (constructor chaining): class Rectangle { int width, height, depth; public Rectangle(int width, int height) { this.width = width; this.height = height; } public Rectangle(int width, int height, int depth) { this(width, height); // Calls 2-param constructor this.depth = depth; } }; (3) Pass current object to a method: class EventSource { public void register(EventListener listener) { listener.setSource(this); // Pass this object } }; (4) Return current object (method chaining/fluent API): class QueryBuilder { private String table, condition, orderBy; public QueryBuilder from(String table) { this.table = table; return this; // Return this for chaining } public QueryBuilder where(String condition) { this.condition = condition; return this; } public QueryBuilder orderBy(String field) { this.orderBy = field; return this; } } // Usage: QueryBuilder qb = new QueryBuilder() .from("users") .where("active = true") .orderBy("name");. In Python, the equivalent is self (explicit first parameter). In JavaScript, this depends on how the function is called (more complex).
Previous
What is the difference between an interface and an abstract class?
Next
What is the difference between composition and inheritance?