Java Keywords this and super

 

The keywords, thisand super help us explicitly refer to a specific field or method that we want to use. Using them we have the full control on whether to call a method or field present in the same class or to call from the immediate superclass. The thiskeyword is used as a reference to the current object which is an instance of the current class. The keyword superreferences an instance of the current class’s super class.

Using “this” as the reference to the current object is useful in situations where a local variable hides, or shadows, a field with the same name. If a method needs to pass the current object to another method, it can do so using the “this” reference. Note that the “this” reference cannot be used in a static context, as static code is not executed in the context of any object.

 

Example 1

See the following example for the keyword “this“.

CounterDemo.java

// Use of “this” keyword

class Counter {
int i = 0;

Counter increment() {
i++;
return this;
}

void print() {
System.out.println("Value of i is : " + i);
}
}

public class CounterDemo extends Counter {
public static void main(String[] args) {
Counter x = new Counter();
x.increment().increment().increment().print();
}
}

Output:

Value of i is : 3

 

Example 2

The following example will show the use of super keyword. In this example Box is the superclass and MatchBox is the subclass. The MatchBox class inherits all the properties and behaviors of Box class. The call to super (width, height, depth) in the parameterized constructor of MatchBox class results in the parameterized constructor of Box class being called.

MatchBox.java

// Use of “this” and super” keywords

class Box {
double width, height, depth;

Box() { }

Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}

void getVolume() {
System.out.println("Volume is : " + width * height * depth);
}
}

public class MatchBox extends Box {
double weight;

MatchBox() { }

MatchBox(double width, double height, double depth, double weight) {
super(width, height, depth);
this.weight = weight;
}

public static void main(String args[]) {
MatchBox mb = new MatchBox(10, 10, 10, 10);
mb.getVolume();
System.out.println("Width of MatchBox is : " + mb.width);
System.out.println("Height of MatchBox is : " + mb.height);
System.out.println("Depth of MatchBox is : " + mb.depth);
System.out.println("Weight of MatchBox is : " + mb.weight);
}
}

Output:

Volume is : 1000.0
Width of MatchBox is : 10.0
Height of MatchBox is : 10.0
Depth of MatchBox is : 10.0
Weight of MatchBox is : 10.0