- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
When should I use the keyword ‘this’ in a Java class?
The this is a keyword in Java which is used as a reference to the object of the current class, within an instance method or a constructor. Using this you can refer the members of a class such as constructors, variables, and methods.

Example
public class This_Example { // Instance variable num int num = 10; This_Example() { System.out.println("This is an example program on keyword this"); } This_Example(int num) { // Invoking the default constructor this(); // Assigning the local variable num to the instance variable num this.num = num; } public void greet() { System.out.println("Hi Welcome to Tutorialspoint"); } public void print() { // Local variable num int num = 20; // Printing the local variable System.out.println("value of local variable num is : "+num); // Printing the instance variable System.out.println("value of instance variable num is : "+this.num); // Invoking the greet method of a class this.greet(); } public static void main(String[] args) { // Instantiating the class This_Example obj1 = new This_Example(); // Invoking the print method obj1.print(); // Passing a new value to the num variable through parametrized constructor This_Example obj2 = new This_Example(30); // Invoking the print method again obj2.print(); } }
Output
This is an example program on keyword this value of local variable num is : 20 value of instance variable num is : 10 Hi Welcome to Tutorialspoint This is an example program on keyword this value of local variable num is : 20 value of instance variable num is : 30 Hi Welcome to Tutorialspoint
- Related Articles
- C++ Program to Show Use of This Keyword in Class
- When Should I use Selenium Grid?
- When should I use a composite index in MySQL?
- When should you use a class vs a struct in C++?
- Can we use "this" keyword in a static method in java?
- When should I write the keyword 'inline' for a function/method in C++?
- What are the 6 ways to use this keyword in Java?
- When should I use MySQL compressed protocol?
- This keyword in Java
- Why "this" keyword cannot be used in the main method of java class?
- When should I use a semicolon after curly braces in JavaScript?
- When should we create a user-defined exception class in Java?
- Is it possible to use this keyword in static context in java?
- When should I use an Inline script and when to use external JavaScript file?
- When to use the ServiceLoader class in a module in Java 9?

Advertisements