this and super keywords in java

Tutorial will help us to get deep knowledge on this and super keywords in java. this keyword is used to access instance attributes and methods of current class and super keyword use to access attributes, methods and constructor of super class.

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

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

Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.

  • Languages: Java, Python
  • Frameworks: J2EE, Spring, Struts 2.0, Hibernate
  • Web Technologies: React, HTML, CSS
  • Analytics: Adobe Analytics
  • Tools & Technologies: IntelliJ, JIRA

🌐 LinkedIn

📝 Blogs

📧 Imran Khan