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.

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

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
Inline Feedbacks
View all comments
Back to top button