[java] Difference between "this" and"super" keywords in Java

What is the difference between the keywords this and super?

Both are used to access constructors of class right? Can any of you explain?

This question is related to java keyword

The answer is


When writing code you generally don't want to repeat yourself. If you have an class that can be constructed with various numbers of parameters a common solution to avoid repeating yourself is to simply call another constructor with defaults in the missing arguments. There is only one annoying restriction to this - it must be the first line of the declared constructor. Example:

MyClass()
{
   this(default1, default2);
}

MyClass(arg1, arg2)
{
   validate arguments, etc...
   note that your validation logic is only written once now
}

As for the super() constructor, again unlike super.method() access it must be the first line of your constructor. After that it is very much like the this() constructors, DRY (Don't Repeat Yourself), if the class you extend has a constructor that does some of what you want then use it and then continue with constructing your object, example:

YourClass extends MyClass
{
   YourClass(arg1, arg2, arg3)
   {
      super(arg1, arg2) // calls MyClass(arg1, arg2)
      validate and process arg3...
   }
}

Additional information:

Even though you don't see it, the default no argument constructor always calls super() first. Example:

MyClass()
{
}

is equivalent to

MyClass()
{
   super();
}

I see that many have mentioned using the this and super keywords on methods and variables - all good. Just remember that constructors have unique restrictions on their usage, most notable is that they must be the very first instruction of the declared constructor and you can only use one.


this is used to access the methods and fields of the current object. For this reason, it has no meaning in static methods, for example.

super allows access to non-private methods and fields in the super-class, and to access constructors from within the class' constructors only.


this keyword use to call constructor in the same class (other overloaded constructor)

syntax: this (args list); //compatible with args list in other constructor in the same class

super keyword use to call constructor in the super class.

syntax: super (args list); //compatible with args list in the constructor of the super class.

Ex:

public class Rect {
int x1, y1, x2, y2;

public Rect(int x1, int y1, int x2, int y2) // 1st constructor 
{ ....//code to build a rectangle }
}

public Rect () {   // 2nd constructor
this (0,0,width,height) // call 1st constructor (because it has **4 int args**), this is another way to build a rectangle 
}


public class DrawableRect extends Rect {

public DrawableRect (int a1, int b1, int a2, int b2) {
super (a1,b1,a2,b2) // call super class constructor (Rect class) 
}
}

super is used to access methods of the base class while this is used to access methods of the current class.

Extending the notion, if you write super(), it refers to constructor of the base class, and if you write this(), it refers to the constructor of the very class where you are writing this code.


this refers to a reference of the current class.
super refers to the parent of the current class (which called the super keyword).

By doing this, it allows you to access methods/attributes of the current class (including its own private methods/attributes).

super allows you to access public/protected method/attributes of parent(base) class. You cannot see the parent's private method/attributes.


super() & this()

  • super() - to call parent class constructor.
  • this() - to call same class constructor.

NOTE:

  • We can use super() and this() only in constructor not anywhere else, any attempt to do so will lead to compile-time error.

  • We have to keep either super() or this() as the first line of the constructor but NOT both simultaneously.

super & this keyword

  • super - to call parent class members(variables and methods).
  • this - to call same class members(variables and methods).

NOTE: We can use both of them anywhere in a class except static areas(static block or method), any attempt to do so will lead to compile-time error.


this is a reference to the object typed as the current class, and super is a reference to the object typed as its parent class.

In the constructor, this() calls a constructor defined in the current class. 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. Calls to other constructors in this way may only be done as the first line in a constructor.

Calling methods works the same way. Calling this.method() calls a method defined in the current class where super.method() will call the same method as defined in the parent class.


From your question, I take it that you are really asking about the use of this and super in constructor chaining; e.g.

public class A extends B {
    public A(...) {
        this(...);
        ...
    }
}

versus

public class A extends B {
    public A(...) {
        super(...);
        ...
    }
}

The difference is simple:

  • The this form chains to a constructor in the current class; i.e. in the A class.

  • The super form chains to a constructor in the immediate superclass; i.e. in the B class.