this
and super are reserved keywords in Java. this
refer to current instance of a class while super
refer to the parent class of that class where super
keyword is used.
1. Java this keyword
this
keyword automatically holds the reference to current instance of a class. It is very useful in scenarios where we are inheriting a method from parent class into child class, and want to invoke method from child class specifically.
We can use this keyword to access static fields in the class as well, but recommended approach to access static fields using class reference e.g. MyClass.STATIC_FIELD.
2. Java super keyword
Similar to this
keyword, super
also is a reserved keyword in Java. It always hold the reference to parent class of any given class.
Using super
keyword, we can access the fields and methods of parent class in any child class.
3. Java this and super keyword example
In this example, we have two classes ParentClass
and ChildClass
where ChildClass extends ParentClass. I have created a method showMyName()
in parent class and override it child class.
Now when we try to invoke showMyName()
method inside child class using this and super keywords, it invokes the methods from current class and parent class, respectively.
public class ParentClass { public void showMyName() { System.out.println("In ParentClass"); } }
public class ChildClass extends ParentClass { public void showMyName() { System.out.println("In ChildClass"); } public void test() { this.showMyName(); super.showMyName(); } }
public class Main { public static void main(String[] args) { ChildClass childObj = new ChildClass(); childObj.test(); } }
Program output.
In ChildClass In ParentClass
In this java tutorial, we learned what are this and super keywords. We also learned to use both keywords in java applications.
Happy Learning !!