Super Keyword
Super in java is a keyword which is a reference variable. It is used to refer to the immediate superclass object or instance variable. The word super came into usage because of the concept of inheritance. The keyword super is placed inside a subclass to call a method from a superclass.
Syntax:
super.a; //for Variable
super.m1(); //for Method
super(); // for Constructor
Remember the points given below:
We must have super class subclass relationship in our program.
Super can be applied to variable, constructors, and method.
Super keyword always represents super class object.
It's generally used to bypass global variable with the same name.
Super call to constructor must be at first line of all constructors.
We strictly cannot call super () in methods in any line; this rule applies only to super() not to super.a or super.m1().
This Keyword
This keyword in java is used inside a method or constructor of a class. It is used to refer to a member of a current object within the instance of a method or constructor.
This represents current class object
Can be applied to variable, constructor and method
Syntax:
this.a; // variable case
this.m1(); // method case
this(10); // To call parameterize constructor of current class object
Remember the points given below:
In case of variable, same class’s global variable will get called
Call to constructor by using this ‘this()’ must be a first line of constructor only. This means that we cannot add ‘this()’ anywhere other than the first line of constructor
inside method ‘this()’ is not allowed, that is call to constructor not allowed by using this.
JVM never puts automatically this() keyword like super()
If we wrote call to constructor explicitly by using ‘this()’ the ‘super()’ call to constructor will not be put by JVM
Recursion will be there as we call the same class constructor using this() in same constructor, which is not allowed in java
Difference between Super and This
Super | This | |
super is reference variable which contains immediate super class objects super also can be used in two ways : a) To invoke immediate super class variable and methods.super.n;super.m1(); b) to invoke immediate super class constructor Ex : | ‘this’ is a reference variable which contains current class objects 'this' can be used in two ways : a) To invoke current class variable and methodsthis.a;this.m1(); b)To invoke current class constructors Ex: | |
super(); | this(); | |
super(10); | this (10,20); | |
super reference variable is instance reference variable and cannot be accessed from static context | This reference variable is instance reference variable and cannot be accessed from static context | |
Call to super() must be at the first line of constructor only | Call to this() must be at the first line of constructor only |