class
Simple use of the keyword this
With this example we are going to demonstrate how to use the keyword this
. Within an instance method or a constructor, this
keyword is a reference to the current object, that is the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this
keyword. In short, a simple way to use the keyword this is the one described below:
- We have created a class,
ThisKeyWord
that has an int field,val
. - It has a method,
ThisKeyWord increase()
that increases its intval
by one and then returns theThisKeyWord
object, usingthis
keyword. It also has a method,value()
, that prints the int field of the class. - We create a new instance of
ThisKeyWord
and call theincrease()
method three times and then itsvalue()
method.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; public class ThisKeyWord { int val = 0; ThisKeyWord increase() { val++; return this; } void value() { System.out.println("val = " + val); } public static void main(String[] args) { ThisKeyWord x = new ThisKeyWord(); x.increase().increase().increase().increase().value(); } }
Output:
val = 4
This was an example of how to use the keyword this
in Java.