library
beginnerThe this & super Keywords
Know every use of this and super: field access, constructor chaining, method calls, and passing the current instance.
this refers to the current object instance. super refers to the parent class. Both have specific uses:
this = pointing at yourself ('I will do this'). super = calling your parent ('Mom, how did you do this?').
Key Concepts
1
this uses:
1. Disambiguate field from parameter: this.name = name in setters/constructors.
2. Call another constructor: this(args) must be first statement in constructor (constructor chaining).
3. Pass current instance: someMethod(this) or return this for fluent APIs.
4. Reference enclosing instance: OuterClass.this in inner classes.
2
super uses:
1. Call parent constructor: super(args) must be first statement. Implicit super() if omitted (parent must have no-arg constructor).
2. Call parent method: super.method() from an overriding method to extend rather than replace behavior.
3. Access parent field: super.field when child shadows it (rare, bad practice).
3
Key rules:
- this() and super() cannot both appear in the same constructor (both must be first statement).
- this cannot be used in static context.
- super() is automatically inserted if not explicitly called and parent has no-arg constructor.
4
A subtle point: you cannot use this before the super() call completes in a constructor — the object isn't fully initialized yet.