Java super Keyword: Calling Parent Class in Inheritance, Must-Know
`super` is a keyword in Java used to access a parent class's members from a subclass, with the core role of connecting the subclass and the parent class. **1. Calling the parent class constructor**: The subclass constructor by default first calls the parent class's no-argument constructor (`super()`). If the parent class has no no-argument constructor or a parameterized constructor needs to be called, `super(parameters)` must be explicitly used and **must be placed on the first line of the subclass constructor**, otherwise a compilation error will occur. **2. Accessing parent class member variables with the same name**: When a subclass variable has the same name as a parent class variable, the subclass variable is accessed by default. Using `super.variableName` explicitly accesses the parent class variable. **3. Calling the parent class's overridden method**: After a subclass overrides a parent class method, the subclass method is called by default. Using `super.methodName()` calls the parent class's overridden method. **Notes**: `super` cannot be used in static methods; `super()` must be on the first line of the subclass constructor; `this()` and `super()` cannot be used simultaneously in a constructor. Mastering `super` enables clear control over a subclass's access to a parent class's members and is key to understanding Java inheritance.
Read More