'super' and 'this' keywords in java


super:
super refers to the parent of the current class (which called the super keyword).
super() calls a constructor defined in the parent class. The constructor may be defined in any parent class, but it will refer to the one overridden closest to the current class.
Calling super.method() will call the same method as defined in the parent class.
There is only one annoying restriction to 'super' keywords - it must be the first line of the declared constructor.

Example for super keyword:
 
class BaseClass{
 
 public BaseClass() {
  System.out.println("Base Class Constructor");
 }

}

public class CurrentClass extends BaseClass {

 public CurrentClass() {
  super();
  System.out.println("Current class Constructor");
 }
 
 public static void main(String[] args) {
  CurrentClass currentClass = new CurrentClass();
 }
}
Output :
Base Class Constructor
Current class Constructor
Even though you don't see it, the default no argument constructor always calls super() first.
 
public CurrentClass() {}
is equivalent to
 
public CurrentClass() {
  super();
}


this:
this refers to a reference of the current class.  In the constructor, this() calls a constructor defined in the current class.
Calling this.method() calls a method defined in the current class.
There is only one annoying restriction to 'this' keywords - it must be the first line of the declared constructor.

Example for this keyword.
 
public class CurrentClass {
 
 public CurrentClass() {
  this(1);
  System.out.println("Current class Constructor");
 }
 
 public CurrentClass(int i){
  System.out.println("Parameter constructor");
 }
 public static void main(String[] args) {
  CurrentClass currentClass = new CurrentClass();
 }
}
Out put :

Parameter constructor
Current class Constructor

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...