Java Arrays Java Strings Java OOPs Java Collection Java 8 Tutorial Java Multithreading Ja
‘this’ reference in Java
Last Updated : 08 Jan, 2024
In Java, ‘this’ is a reference variable that refers to the current object, or
can be said “this” in Java is a keyword that refers to the current object
instance. It can be used to call current class methods and fields, to pass
an instance of the current class as a parameter, and to differentiate
between the local and instance variables. Using “this” reference can
improve code readability and reduce naming conflicts.
Java this reference Example
In Java, this is a reference variable that refers to the current object on
which the method or constructor is being invoked. It can be used to
access instance variables and methods of the current object.
Miss Visual Basic? Try Xojo.
Build Apps With Xojo
Rapid Application Development For macOS,
Windows & Linux. Cross-Platform And
Native!
Xojo, Inc.
Learn More
Below is the implementation of this reference:
Java
// Java Program to implement Open In App
// Java this reference
// Driver Class
public class Person {
// Fields Declared
String name;
int age;
// Constructor
Person(String name, int age)
{
this.name = name;
this.age = age;
}
// Getter for name
public String get_name() { return name; }
// Setter for name
public void change_name(String name)
{
this.name = name;
}
// Method to Print the Details of
// the person
public void printDetails()
{
System.out.println("Name: " + this.name);
System.out.println("Age: " + this.age);
System.out.println();
}
// main function
public static void main(String[] args)
{
// Objects Declared
Person first = new Person("ABC", 18);
Person second = new Person("XYZ", 22);
first.printDetails();
second.printDetails();
first.change_name("PQR");
Openhas
System.out.println("Name In App
been changed to: "
+ first.get_name());
}
}
Output
Name: ABC
Age: 18
Name: XYZ
Age: 22
Name has been changed to: PQR
Explanation
In the above code, we have defined a Person class with two private fields
name and age. We have defined the Person class constructor to initialize
these fields using this keyword. We have also defined getter and setter
methods for these fields which use this keyword to refer to the current
object instance.
In the printDetails() method, we have used this keyword to refer to the
current object instance and print its name, age, and object reference.
Open In App
In the Main class, we have created two Person objects and called the
printDetails() method on each object. The output shows the name, age,
and object reference of each object instance.
Methods to use ‘this’ in Java
Following are the ways to use the ‘this’ keyword in Java mentioned below:
Using the ‘this’ keyword to refer to current class instance variables.
Using this() to invoke the current class constructor
Using ‘this’ keyword to return the current class instance
Using ‘this’ keyword as the method parameter
Using ‘this’ keyword to invoke the current class method
Using ‘this’ keyword as an argument in the constructor call
1. Using ‘this’ keyword to refer to current class instance variables
Java
// Java code for using 'this' keyword to
// refer current class instance variables
class Test {
int a;
int b;
// Parameterized constructor
Test(int a, int b)
{
this.a = a;
this.b = b;
}
void display()
{
// Displaying value of variables a and b
System.out.println("a = " + a + " b = " + b);
}
public static void main(String[] args)
{
Test object = new Test(10,
Open In20);
App
object.display();
}
}
Output
a = 10 b = 20
2. Using this() to invoke current class constructor
Java
// Java code for using this() to
// invoke current class constructor
class Test {
int a;
int b;
// Default constructor
Test()
{
this(10, 20);
System.out.println(
"Inside default constructor \n");
}
// Parameterized constructor
Test(int a, int b)
{
this.a = a;
this.b = b;
System.out.println(
"Inside parameterized constructor");
}
public static void main(String[] args)
{
Test object = new Test();
}
Open In App
}
Output
Inside parameterized constructor
Inside default constructor
3. Using ‘this’ keyword to return the current class instance
Java
// Java code for using 'this' keyword
// to return the current class instance
class Test {
int a;
int b;
// Default constructor
Test()
{
a = 10;
b = 20;
}
// Method that returns current class instance
Test get() { return this; }
// Displaying value of variables a and b
void display()
{
System.out.println("a = " + a + " b = " + b);
}
public static void main(String[] args)
{
Test object = new Test();
object.get().display();
} Open In App
}
Output
a = 10 b = 20
4. Using ‘this’ keyword as a method parameter
Java
// Java code for using 'this'
// keyword as method parameter
class Test {
int a;
int b;
// Default constructor
Test()
{
a = 10;
b = 20;
}
// Method that receives 'this' keyword as parameter
void display(Test obj)
{
System.out.println("a = " + obj.a
+ " b = " + obj.b);
}
// Method that returns current class instance
void get() { display(this); }
// main function
public static void main(String[] args)
{
Test object = new Test();
object.get();
}
Open In App
}
Output
a = 10 b = 20
5. Using ‘this’ keyword to invoke the current class method
Java
// Java code for using this to invoke current
// class method
class Test {
void display()
{
// calling function show()
this.show();
System.out.println("Inside display function");
}
void show()
{
System.out.println("Inside show function");
}
public static void main(String args[])
{
Test t1 = new Test();
t1.display();
}
}
Output
Open In App
Inside show function
Inside display function
6. Using ‘this’ keyword as an argument in the constructor call
Java
// Java code for using this as an argument in constructor
// call
// Class with object of Class B as its data member
class A {
B obj;
// Parameterized constructor with object of B
// as a parameter
A(B obj)
{
this.obj = obj;
// calling display method of class B
obj.display();
}
}
class B {
int x = 5;
// Default Constructor that create an object of A
// with passing this as an argument in the
// constructor
B() { A obj = new A(this); }
// method to show value of x
void display()
{
System.out.println("Value of x in Class B : " + x);
}
public static void main(String[] args)
{
B obj = new B(); Open In App
}
}
Output
Value of x in Class B : 5
Advantages of using ‘this’ reference
There are certain advantages of using ‘this’ reference in Java as
mentioned below:
1. It helps to distinguish between instance variables and local variables
with the same name.
2. It can be used to pass the current object as an argument to another
method.
3. It can be used to return the current object from a method.
4. It can be used to invoke a constructor from another overloaded
constructor in the same class.
Disadvantages of using ‘this’ reference
Although ‘this’ reference comes with many advantages there are certain
disadvantages of also:
1. Overuse of this can make the code harder to read and understand.
2. Using this unnecessarily can add unnecessary overhead to the
program.
3. Using this in a static context results in a compile-time error.
4. Overall, this keyword is a useful tool for working with objects in Java,
but it should be used judiciously and only when necessary.
This article is contributed by Mehak Narang and Amit Kumar.
Open In App
Comment More info
Next Article
Advertise with us
static Keyword in Java
Similar Reads
Java Programs - Java Programming Examples
In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic
Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers…
8 min read
Java Basic Programs
Java Pattern Programs
Java Conversion Programs
Java Classes and Object Programs
Classes and Objects in Java
In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used
to represent real-world concepts and entities. The class represents a group of objects having similar…
11 min read
Abstract Class in Java
In Java, abstract class is declared with the abstract keyword. It may have both abstract and non-
abstract methods(methods with bodies). An abstract is a Java modifier applicable for classes and…
10 min read
Singleton Method Design Pattern in Java
Open In App
In object-oriented programming, a java singleton class is a class that can have only one object (an
instance of the class) at a time. After the first time, if we try to instantiate the Java Singleton classes,…
8 min read
Java Interface
An Interface in Java programming language is defined as an abstract type used to specify the
behavior of a class. An interface in Java is a blueprint of a behavior. A Java interface contains static…
9 min read
Encapsulation in Java
Encapsulation in Java is a fundamental OOP (object-oriented programming) principle that combines
data and methods in a class. It allows implementation details to be hidden while exposing a public…
[ ]
7 min read
Inheritance in Java
Java, Inheritance is an important pillar of OOP(Object-Oriented Programming). It is the mechanism in
Java by which one class is allowed to inherit the features(fields and methods) of another class. In…
12 min read
Abstraction in Java
Abstraction in Java is the process of hiding the implementation details and only showing the essential
functionality or features to the user. This helps simplify the system by focusing on what an object…
9 min read
Difference Between Data Hiding and Abstraction in Java
Abstraction Is hiding the internal implementation and just highlight the set of services. It is achieved
by using the abstract class and interfaces and further implementing the same. Only necessarily…
6 min read
Polymorphism in Java
The word ‘polymorphism’ means ‘having many forms’. In Java, polymorphism refers to
the ability of a message to be displayed in more than one form. This concept is a key feature of…
6 min read
Method Overloading in Java
In Java, Method Overloading allows different methods to have the same name, but different
signatures where the signature can differ by the number of input parameters or type of input…
9 min read Open In App
Overriding in Java
Overriding in Java occurs when a subclass implements a method which is already defined in the
superclass or Base Class. The method in the subclass must have the same signature as in the…
13 min read
Super Keyword in Java
The super keyword in Java is a reference variable that is used to refer to parent class when we're
working with objects. You need to know the basics of Inheritanceand Polymorphism to understand t…
Â
8 min read
'this' reference in Java
In Java, 'this' is a reference variable that refers to the current object, or can be said "this" in Java is a
keyword that refers to the current object instance. It can be used to call current class methods and…
6 min read
static Keyword in Java
The static keyword in Java is mainly used for memory management. The static keyword in Java is
used to share the same variable or method of a given class. The users can apply static keywords wit…
9 min read
Access Modifiers in Java
In Java, Access modifiers helps to restrict the scope of a class, constructor, variable, method, or data
member. It provides security, accessibility, etc. to the user depending upon the access modifier used…
6 min read
Java Methods Programs
Java Searching Programs
Java 1-D Array Programs
Java 2-D Arrays (Matrix) Programs
Java String Programs
Open In App
Corporate & Communications
Address:
A-143, 7th Floor, Sovereign Corporate
Tower, Sector- 136, Noida, Uttar
Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante
Apartment, Sector 137, Noida,
Gautam Buddh Nagar, Uttar Pradesh,
201305
Advertise with us
Open In App
Company Languages
About Us Python
Legal Java
Privacy Policy C++
In Media PHP
Contact Us GoLang
Advertise with us SQL
GFG Corporate Solution R Language
Placement Training Program Android Tutorial
GeeksforGeeks Community Tutorials Archive
DSA Data Science & ML
Data Structures Data Science With Python
Algorithms Data Science For Beginner
DSA for Beginners Machine Learning
Basic DSA Problems ML Maths
DSA Roadmap Data Visualisation
Top 100 DSA Interview Problems Pandas
DSA Roadmap by Sandeep Jain NumPy
All Cheat Sheets NLP
Deep Learning
Web Technologies Python Tutorial
HTML Python Programming Examples
CSS Python Projects
JavaScript Python Tkinter
TypeScript Web Scraping
ReactJS OpenCV Tutorial
NextJS Python Interview Question
Bootstrap Django
Web Design
Computer Science DevOps
Operating Systems Git
Computer Network Linux
Database Management System AWS
Software Engineering Docker
Digital Logic Design Kubernetes
Engineering Maths Azure
Software Development GCP
Software Testing DevOps Roadmap
System Design Inteview Preparation
High Level Design Competitive Programming
Low Level Design Open In App Top DS or Algo for CP