This Keyword
What is this?
- this is a Keyword in Java that refers to the current object of the class.
- It is a fundamental concept in object-oriented programming.
When we use this?
- When local variables and instance variables have the same name.
- can be used within a constructor to call another constructor of the same class.
- When you want to pass the current object to another method or constructor.
How it will be used?
- this.variable --- access current object variable.
- this.method() --- call a method of the same class.
- this() → call another constructor of the same class.
Where we use?
- In constructors ---- to call another constructor.
- In instance methods ---- to access variables/methods of the same object.
- When passing the current object ---- as a parameter.
Why we use?
- To reuse constructors instead of duplicating code.
- To remove confusion between local and instance variables.
super keyword
What is super?
- super is a keyword that refers to the parent class object.
When we use super?
- When you want to call the parent class constructor.
- When a child class overrides a method but you still need the parents one.
- When parent and child class variables have the same name.
How it will be used?
- super.variable ---- access parent class variable.
- super.method() ---- call parent class method.
- super() ---- call parent class constructor (must be first statement).
Where we use?
- inside the child class only.
- super() can only be in constructors.
- super.variable/method can be inside child methods.
Why we use?
- To avoid code duplication in constructors.
- To access hidden parent members that are overridden in child.
- To achieve reusability of parent class features.
Top comments (0)