This post originated from an RSS feed registered with Java Buzz
by Javin Paul.
Original Post: Difference between this and super keywords in Java
Feed Title: Java67
Feed URL: http://www.java67.com/feeds/posts/default?alt=rss
Feed Description: Java and technology tutorials, tips, questions for all programmers.
this and super are two
special keywords in Java, which is used to represent current instance of a
class and it's super class. Java Programmers often confused between them and
not very familiar with there special properties, which is asked at various core
Java interviews. Couple of questions, which I remember about this and super keyword
isthat, Can we reassign this in Java?and difference
between this and super keyword in Java. Do you want to try that? Ok, I
am not giving answer now, rather I will let you know answer at the end of this
post. As I said in first line, main difference between this and super in Java is
that, this represent current instance of a class, while super represent
current instance of parent class. Now where does this and super variables
used, well you might have seen examples of calling one constructor from other
i.e. constructor
chaining, that's achieved by using this and super keyword.
You can use this() to call no argument constructor
of same class, while super() to call no argument or default
constructor of parent class. By the way, call is not limited to only no
argument constructor, you can call any constructor by passing appropriate
parameters. We will see example of using this and super in a
while. Another use of this and super in Java is for accessing instance variables of a class and it's parent. By the
way, you can also access them even without prefixing super and this, if they
are not ambiguous in current block e.g. if there is no local
variable of same name exists in that block, but in case of ambiguity they
provide explicit reference and are more readable. Classic example of using this is inside
a constructor,
which accepts a parameter of same name as an instance variable. In this post,
we will learn about more differences between super and this in Java
and take a look at some of the use cases.