Java – this()

this:

  • It is default reference variable.
  • It is used to access instance variables and methods of same class.
  • It must be used from instance area.

this():

  • this() is used to invoke the same class constructor.
  • It must be used in constructor only.
  • Call to this() must be the first statement.
class Pro
{
            Pro(){
                        System.out.println(“Zero args constructor”);
            }
            Pro(int x){
                        this();
                        System.out.println(“Args constructor”);
            }
            public static void main(String args[]){
                        new Pro(10);
            }
}

Invoking multiple constructors results Error:

Scroll to Top