In this tutorial, we are going to discuss the Difference Between Super And This Keyword In Java, Where the super keyword is used for referring to the parent class and this keyword is used for referring to the existing same class.
What Is The Use Of Super Keyword
As we know there is a concept of inheritance where the child class inherits all the properties of the parent class and the child class has all the properties of the parent class as well as of properties of itself that we call it will be more evolved.
So here comes the requirement of a super keyword when we need to access the member of the parent class in the child class.
Take an example that lets us be required to get the value of a variable in the child class but it is stored in the parent class then we can not use it directly we need to use the keyword super for getting the value in the child class.
There are some more uses of a super keyword like calling the function of the parent class from the child class.
We can also call the Constructor of the parent class with the help of the super keyword.
Let’s see with an example:
class Base { int a = 100; } class Sup1 extends Base { int a = 200; void Show() { System.out.println(a); System.out.println(a); } public static void main(String[] args) { new Sup1().Show(); } }
Use Of This Keyword
‘This’ is also a keyword that is of super but the only difference between them is as super is used for accessing the member functions and variables of the parent class. This key keyword is used for referring to the member functions and variables of the same class.
Let’s understand more clearly with an example
public class MyClass { String name; public class MyClass { String name; public String getOuterName() { return MyClass.this.name; } } }
As there are two functions of the same name one in the parent class and another function in the child class with the same name so when we use this keyword it will be calling the function of the same class where it is used.
Whereas in the case of the super keyword, it will call the function of the parent class, Which is a major difference in both keywords.
Learn More About the Difference Between Super And This Keyword In Java: Super and This keywords
And also Visit JAVA TUTORIAL for explanations of other java problems.