Difference between this and super keyword in java with example
In Java, both
super are keywords used to refer to objects, but they are used in different contexts and have different meanings:
- Refers to the Current Object:
thisrefers to the current instance of the class. It represents the object on which the currently executing method was invoked.
- Usage: It is often used to differentiate between instance variables and local variables when they have the same name.
thisis used to access instance variables and methods of the current object.
- Constructor Chaining:
thisis used to call another constructor in the same class.
- Refers to the Superclass Object:
superrefers to the superclass object of the current subclass object. It is used to access superclass members (variables and methods) that are hidden by the subclass.
- Usage: It is often used to invoke superclass methods, access superclass fields, and call the superclass constructor.
- Calling Superclass Constructor:
superis used to call the constructor of the superclass from the subclass constructor.
this refers to the current object and is used to access instance variables, invoke methods, and call constructors within the same class.
super refers to the superclass object and is used to access superclass members and call superclass constructors in a subclass.