2011-12-11

Differences between this and super keyword in java

The following are the similarities and differences between this and super keyword. One thing keep in mind that we cannot print 'super' like 'this' why because super class non-static members memory doesn't have hashcode. And also keep in mind that super method is different from super keyword. super method is used to call super class constructor where as super keyword is used to access super class members.


this(current class)super(super class)
1.It is a keyword used to store current object reference.1.It is a keyword used to store super class object in sub class.
2.Pre define instance variable used to hold current object reference.2.Pre define instance variable used to hold super class object reference through sub class object.
3.Used to separate state of multiple objects of same class and also used to separate local variables and class level variables in a non-static method if both have same name.3.Used to seperate super class and subclass members if both have same name.
4.It must be used explicitly if non-static variables and local variables or parameter name is same.4.It must be used explicitly if super class and sub class members have same names.
5.Can't be referred from static context. It can be printed, means can be called from System.out.println. For example System.out.println(this.x);5.Can't be referred from static context.It can't be printed, means cannot be called from System.out.println. For example System.out.println(super.x); it leads to compile time error.

Loading

Enter your Email here: