This keyword is used to refer current object
- It can be used to refer current class instance variable.
- It can be used to invoke the current class method (implicitly)
- It can be used to invoke the current class constructor.
- It can be passed as an argument in the method call.
- It can be passed as an argument in the constructor call.
- It can be used to return the current class instance from the method
Output:
Here in this sample when the test object t is instantiated the Parameterized constructor is executed thus the value of x and y is assigned to 10 1nd 20 respectively next statement executes the display method which will print the value of x and y
Output:
In this example, we have two constructors, a default constructor, and a parameterized constructor. When we do not pass any parameter while creating the object, using a new keyword default constructor is invoked which has the statement this(10,20) will call the parameterized constructor and print the statement” Inside parameterized constructor”. After that statement inside the default constructor is printed, however when you pass a parameter the parameterized constructor that matches with the passed parameters list gets invoked.
Output:
In this example when the object s is instantiated the default constructor gets invoked which assigns the value of x and y later when the next statement gets executed get method returns the value of the current instance which is displayed through the statements in the display method