Lesson 23 / 38
this vs super, In Depth
Pin down every use of this and super — referring to the current instance, chaining constructors, disambiguating fields, and reaching a parent's overridden method.
What each one means
this refers to the current object — useful to disambiguate a field from a same-named parameter, to pass the current instance elsewhere, or to chain to another constructor with this(...). super refers to the immediate superclass part of the current object — used for super.method() and super(...).
Both together
super.describe() calls the parent's version even though Dog overrides it, letting the child extend rather than fully replace the behaviour.
class Animal {
protected String name;
Animal(String name) { this.name = name; }
String describe() { return "Animal: " + name; }
}
class Dog extends Animal {
Dog(String name) { super(name); }
@Override String describe() {
return super.describe() + " (a dog)";
}
}The rules
this(...) and super(...) can each only appear as the first statement of a constructor, and you can never use both in the same one — the object needs exactly one initialization path per constructor.