Java : Uses of this and super

In this post, I will list out possible uses of these two operators. Before that let me give brief details

  • These are keywords having special semantic/meaning in language.
  • Most uses are accessing the members or invoking the constructor.
  • Uses of are valid within- Constructor, Instance initializer block, Instance initializer expression. Use in constructs than these are invalid and compiler will throw error accordingly.

Uses of this 

It is operator which represents the value which is reference to object to which instance method is invoked (in case of method or block scope) or object in the construction (constructor scope)

In simple words, when using this operator you have access to invoking object, to which you can access any instance member on that.

Access the members

You may modify access to members using this operator to explicitly saying that accessing the member of that class. Without modifying it will access only member which belongs to same class

Basic syntax is this.<member>

Following snippet shows usage

public class Shape {
int length;
int width;
public void setLength(int length) {
// access the instance variable
this.length = length;
}
public void setWidth(int width) {
// access the instance variable
this.width = width;
}
public void buildRectangle() {
// access the instance member method
this.setLength(5);
this.setWidth(4);
}
}
view raw ThisOperator3.java hosted with ❤ by GitHub

Following program shows the this reference value and Shape reference variable, to which method is invoked, are same
public class Shape {
private void printThis() {
// prints invoking object
System.out.println(this);
}
public static void main(String[] args) {
Shape shape = new Shape();
// print the shape reference
System.out.println(shape);
// print the shape reference inside method
shape.printThis();
}
}
// after execution this will print
// Shape@19821f
// Shape@19821f
// meaning that both are similar object
view raw ThisOperator4.java hosted with ❤ by GitHub

Above code makes clears that this  is the reference to invoking object

Access member variable in case parameter name is same as field name

There may be the case that you are having same name to parameter as that of field (mostly in constructor parameter) for readability purpose. Lets look at following code snippet

public class Shape {
int length;
int width;
private Shape(int length, int width) {
length = length;
width = width;
}
}
view raw ThisOperator1.java hosted with ❤ by GitHub

This will not result into assignment to field because instance field is hidden by local variable as it is in local block scope.

To override the local variable scope, we should make use this operator  as shown following code 

public class Shape {
int length;
int width;
private Shape(int length, int width) {
// access member variable incase the
// field name and parameter name are same
this.length = length;
this.width = width;
}
}
view raw ThisOperator2.java hosted with ❤ by GitHub

Invoke the another constructor

It may be case that you want to create new constructor which is doing same as that of another constructor but with something different and you don’t want to duplicate code the constructor code

We can have this , using syntax : this ( <param> )

Following code shows usage 

public class Shape {
private int length;
private int width;
private Shape(int length, int width) {
// this constructs rectangle
this.length = length;
this.width = width;
}
private Shape(int length) {
// Constructs the square
// by invoking the another constructor
this(length, length);
}
}
view raw ThisOperator5.java hosted with ❤ by GitHub

Remember, the invocation must be very first statement in the constructor. If it is not then such attempt is invalid.

Use of super 

This operator comes into use when class has inheritance and want to access the member of the super class in subclass which are accessible.

Access the hidden member variable

When in a sub class, you are having the variable with same name as that of in super class then super class variable is hidden in the subclass. Therefore, the any access to that variable in subclass will result in to one in the subclass.

So, to access the hidden variable from super class we have to use super as shown in following code snippet.

public class SuperClass {
int i = 1;
}
view raw SuperOperator1.java hosted with ❤ by GitHub
public class SubClasss extends SuperClass {
int i = 2;
public void display() {
System.out.println(i); // result 2
System.out.println(super.i); // result 1
}
}
view raw SuperOperator2.java hosted with ❤ by GitHub

Access the overridden method from super class

This same as accessing the variable as above

lets look at following code snippet

public class SuperClass {
public void display() {
System.out.println("Super");
}
}
view raw SuperOP.java hosted with ❤ by GitHub
public class SubClasss extends SuperClass {
public void display() {
System.out.println("Sub");
}
private void access() {
display(); // invokes one in SubClass
super.display(); // invokes one in SuperClass
}
}
view raw SuperOP1.java hosted with ❤ by GitHub

Invoking the super class constructor

Like invoking another constructor of same class as in this(), you can invoke super class constructor. Using syntax , super(<param>)

Lets look at following code snippet

public class SuperClass {
public SuperClass() {
System.out.println("SuperClass Constr with no params");
}
public SuperClass(int a, int b) {
System.out.println("SuperClass Constr with two params");
}
}
view raw SuperOP3.java hosted with ❤ by GitHub
public class SubClasss extends SuperClass {
public SubClasss() {
super(5, 4);
System.out.println("SubClasss Constr with no params");
}
public SubClasss(int a) {
System.out.println("SubClasss Constr with one params");
}
public static void main(String[] args) {
new SubClasss();
System.out.println();
new SubClasss(5);
}
}
view raw SuperOP4.java hosted with ❤ by GitHub
Result of execution
SuperClass Constr with two params
SubClasss Constr with no params
SuperClass Constr with no params
SubClasss Constr with one params
view raw zresult.txt hosted with ❤ by GitHub

When you write any constructor, having statements except for this(), then compiler always puts the call to super class default constructor which is super().

Once last point, When using super or this for constructor invocation one of them must be used.

4 thoughts on “Java : Uses of this and super

Add yours

  1. Pingback: JavaPins

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: