0% found this document useful (0 votes)
2 views3 pages

Use of This Keyword in Java

The 'this' keyword in Java refers to the current object of a class and serves multiple purposes, including distinguishing instance variables from local variables, invoking methods and constructors within the same class, passing the current object as a parameter, and returning the current object for method chaining. Examples illustrate each of these uses effectively. Overall, 'this' enhances clarity and functionality in object-oriented programming in Java.

Uploaded by

akshayryakawar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views3 pages

Use of This Keyword in Java

The 'this' keyword in Java refers to the current object of a class and serves multiple purposes, including distinguishing instance variables from local variables, invoking methods and constructors within the same class, passing the current object as a parameter, and returning the current object for method chaining. Examples illustrate each of these uses effectively. Overall, 'this' enhances clarity and functionality in object-oriented programming in Java.

Uploaded by

akshayryakawar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Use of 'this' Keyword in Java

The 'this' keyword in Java is used to refer to the current object of the class. It is commonly used for

the following purposes:

1. Refer to instance variables:

When local variables have the same name as instance variables, 'this' is used to distinguish them.

Example:

class Student {

int id;

String name;

Student(int id, String name) {

this.id = id;

this.name = name;

2. Invoke current class method:

'this' can be used to call another method of the same class.

Example:

void display() {

System.out.println("Display method");

}
void show() {

this.display();

3. Invoke current class constructor:

'this()' can be used to call another constructor of the same class.

Example:

class Example {

Example() {

this(10);

System.out.println("Default constructor");

Example(int x) {

System.out.println("Parameterized constructor: " + x);

4. Pass current object as a parameter:

'this' can be passed as an argument in method or constructor calls.

Example:

void show() {

helper(this);

}
void helper(Student obj) {

System.out.println(obj.id);

5. Return current object:

Useful in method chaining.

Example:

class Test {

Test getObject() {

return this;

You might also like