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
is a reference to the object typed as the current class, and super
is a reference to the object typed as its parent class.
In the constructor, this()
calls a constructor defined in the current class. super()
calls a constructor defined in the parent class. The constructor may be defined in any parent class, but it will refer to the one overridden closest to the current class. Calls to other constructors in this way may only be done as the first line in a constructor.
Calling methods works the same way. Calling this.method()
calls a method defined in the current class where super.method()
will call the same method as defined in the parent class.
this
is used to access the methods and fields of the current object. For this reason, it has no meaning in static methods, for example.
super
allows access to non-private methods and fields in the super-class, and to access constructors from within the class' constructors only.
this
refers to a reference of the current class.
super
refers to the parent of the current class (which called the super
keyword).
By doing this
, it allows you to access methods/attributes of the current class (including its own private methods/attributes).
super
allows you to access public/protected method/attributes of parent(base) class. You cannot see the parent's private method/attributes.