Java Made Clear: Difference between this and super Example

Java Made Clear: Difference between this and super Example


Basically, both this vs super Java are keywords performing different jobs.
  1. this keyword refers an object
  2. super keyword refers a super class variable or method

A) Meaning, Purpose and Usage of this Keyword

this refers an object, that too, a current object. What is current object? To understand better, let us write a small program to see the affect of non-presence of this keyword.

this vs super Java

this.floors = floors;

The beauty in the code is the instance variable floors is clashing with local variable floors. Whenever, both instance variable and local variable are the same, use this keyword with instance variable as this.floors. If not, what happens? Just replace, this.floors = floors with floors = floors, the output will be 0. Why? In floors = floors, both floors are treated as local variables. That is, local variable is assigned to itself. The local variable value of 5 is not reaching the instance variable floors. If not reached, the instance variable b1.floors prints 0, the default value assigned by JVM.

Let us see the meaning of current object. When the method, numberOfFloors(int) is called with object b1, then b1 is known as current object. JVM at runtime, replaces this.floors with b1.floors. That is, this keyword becomes the current object b1.

Small precaution is this keyword cannot be applied with static variables or static methods.

Now everything happened within the same class. If happens in between super class and subclass (clashing of variables), just use super keyword. Next code illustrates.

B) Meaning, Purpose and Usage of super Keyword

Sometimes it may happen, the super class variable and subclass variable may happen the same (clashes). If happens the same, subclass object cannot access super variable. See the code.

this vs super Java

Observe, both super class Tree and subclass Mango are having fruits variable. If subclass object m1 calls fruits, it prints 8000 but not of super class 5000. Ofcourse, it is right by common sense also. But, if the subclass would like to have both fruits values, then it should use super.fruits as in getFruits() method.

The same case with methods also when they are overridden by subclass.

Small precaution is super keyword cannot be applied with static variables or static methods. By the by, by rule static variables and static methods cannot be overridden (then where is the question of using super keyword).

Note: this and super cannot be used from static context. That is, super cannot be used from static methods including main().

View All for Java Differences on 90 Topics

Leave a Reply

Your email address will not be published. Required fields are marked *