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 int val by one and then returns the ThisKeyWord object, using this keyword. It also has a method, value(), that prints the int field of the class.
  • We create a new instance of ThisKeyWord and call the increase() method three times and then its value() 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.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button