Java this and super keywords

this keyword is used to access instance attributes and methods of current class.

this keyword doesn’t work inside static method and block. This keyword can be pass as a parameter in the method and constructor.

As this is final, we cannot assign any value to this keyword.

Problem: What will happen if we don’t use this key word inside constructor.

In below code snippet, we are assigning constructor argument to the same variable and not to the instance variable. Due to absence of this keyword in MyClass(int employeeId) constructor, we are not assigning the employeeId to class level variable. Hence, printing the employeeId in main method is giving us the output as 0.

OUTPUT:

Let’s make above program correct:

Below is the code snippet where we are assigning constructor argument value to instance variable using this keyword inside MyClass(int employeeId) constructor.

OUTPUT:

super keyword

super keyword use to access attributes, methods and constructor of super class.

Access methods and variables of parent class using super keyword in subClass:

OUTPUT:

Using super we can access the no-arg and parameterized constructors of parent class. super should be first statement inside a constructor of subClass.

OUTPUT:

Difference between this and super:

One more example to understand the difference in between this and super keyword:

This keyword implementation:

OUTPUT:

Imran Khan, Adobe Community Advisor, AEM certified developer and Java Geek, is an experienced AEM developer with over 11 years of expertise in designing and implementing robust web applications. He leverages Adobe Experience Manager, Analytics, and Target to create dynamic digital experiences. Imran possesses extensive expertise in J2EE, Sightly, Struts 2.0, Spring, Hibernate, JPA, React, HTML, jQuery, and JavaScript.

0