What is the difference between the keywords this
and super
?
Both are used to access constructors of class right? Can any of you explain?
this keyword mainly represents the current instance of a class. On other hand super keyword represents the current instance of a parent class. this keyword used to call default constructor of the same class. super keyword used to call default constructor of the parent class.
super() acts as immediate parent class constructor and should be first line in child class constructor. this() acts as current class constructor and can be used in parametrized constructors. When invoking a superclass version of an overridden method the super keyword is used.
super refers to the base class that the current class extends. this refers to the current class instance.
In Java, both this and this() are completely different from each other. this keyword is used to refer to the current object, i.e. through which the method is called. this() is used to call one constructor from the other of the same class.
Lets consider this situation
class Animal { void eat() { System.out.println("animal : eat"); } } class Dog extends Animal { void eat() { System.out.println("dog : eat"); } void anotherEat() { super.eat(); } } public class Test { public static void main(String[] args) { Animal a = new Animal(); a.eat(); Dog d = new Dog(); d.eat(); d.anotherEat(); } }
The output is going to be
animal : eat dog : eat animal : eat
The third line is printing "animal:eat" because we are calling super.eat()
. If we called this.eat()
, it would have printed as "dog:eat".
super
is used to access methods of the base class while this
is used to access methods of the current class.
Extending the notion, if you write super()
, it refers to constructor of the base class, and if you write this()
, it refers to the constructor of the very class where you are writing this code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With