What is the difference between the keywords this
and super
?
Both are used to access constructors of class right? Can any of you explain?
What is the difference between the keywords this
and super
?
Both are used to access constructors of class right? Can any of you explain?
When writing code you generally don't want to repeat yourself. If you have an class that can be constructed with various numbers of parameters a common solution to avoid repeating yourself is to simply call another constructor with defaults in the missing arguments. There is only one annoying restriction to this - it must be the first line of the declared constructor. Example:
As for the
super()
constructor, again unlikesuper.method()
access it must be the first line of your constructor. After that it is very much like thethis()
constructors, DRY (Don't Repeat Yourself), if the class you extend has a constructor that does some of what you want then use it and then continue with constructing your object, example:Additional information:
Even though you don't see it, the default no argument constructor always calls
super()
first. Example:is equivalent to
I see that many have mentioned using the
this
andsuper
keywords on methods and variables - all good. Just remember that constructors have unique restrictions on their usage, most notable is that they must be the very first instruction of the declared constructor and you can only use one.From your question, I take it that you are really asking about the use of
this
andsuper
in constructor chaining; e.g.versus
The difference is simple:
The
this
form chains to a constructor in the current class; i.e. in theA
class.The
super
form chains to a constructor in the immediate superclass; i.e. in theB
class.this
refers to a reference of the current class.super
refers to the parent of the current class (which called thesuper
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.this keyword use to call constructor in the same class (other overloaded constructor)
syntax: this (args list); //compatible with args list in other constructor in the same class
super keyword use to call constructor in the super class.
syntax: super (args list); //compatible with args list in the constructor of the super class.
Ex:
Lets consider this situation
The output is going to be
The third line is printing "animal:eat" because we are calling
super.eat()
. If we calledthis.eat()
, it would have printed as "dog:eat".super
is used to access methods of the base class whilethis
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 writethis()
, it refers to the constructor of the very class where you are writing this code.