- this keyword in Java
- this keyword with a field(Instance Variable)
- Example of Variable Hiding
- Example of this keyword in Java for Variable Hiding
- this Keyword with Constructor
- Example of this with Constructor
- this Keyword with Method
- Example of this keyword with Method
- Example of this keyword as a Method parameter
- References 1- Official Document
- 70 thoughts on “this keyword in Java”
- Using the this Keyword
- Using this with a Field
- Using this with a Constructor
- this Keyword in Java: What is & How to use with Example
- Understand ‘this’ keyword with an example.
- this keyword in java with example
- This keyword can be used for instance variables
- This keyword can be used to call the overloaded constructor
- this keyword can be used return object of the class
- Related posts
- How to Get Variable From Another Class in Java
- Increment for Loop by 2 in Java
- Return ArrayList in Java
- Check if Object Is Null in Java
- How to Print Multiple Variables in Java
- What is == in java
- Multiple classes in one file in Java
- How to break out of nested loops in Java
- public static void main(String[] args) – Java main method
- Top 20 Java Projects for Beginners
- Was this post helpful?
- Share this
- Related Posts
- Author
- Related Posts
- How to Get Variable From Another Class in Java
- Increment for Loop by 2 in Java
- Return ArrayList in Java
- Check if Object Is Null in Java
- How to Print Multiple Variables in Java
- What is == in java
this keyword in Java
this is a keyword in Java. It can be used inside the method or constructor of a class. It(this) works as a reference to the current object, whose method or constructor is being invoked. This keyword can refer to any member of the current object from within an instance method or a constructor.
this keyword with a field(Instance Variable)
this keyword in java can be handy in the handling of Variable Hiding. We can not create two instances/local variables with the same name. However, it is legal to create one instance variable & one local variable or Method parameter with the same name. In this scenario, the local variable will hide the instance variable; this is called Variable Hiding.
Example of Variable Hiding
class JBT < int variable = 5; public static void main(String args[]) < JBT obj = new JBT(); obj.method(20); obj.method(); >void method(int variable) < variable = 10; System.out.println("Value of variable :" + variable); >void method() < int variable = 40; System.out.println("Value of variable :" + variable); >>
The output of the above program
Value of variable :10 Value of variable :40
As you can see in the example above, the instance variable is hiding, and the value of the local variable (or Method Parameter) is displayed, not the instance variable. To solve this problem, use this keyword to point to the instance variable instead of the local variable.
Example of this keyword in Java for Variable Hiding
class JBT < int variable = 5; public static void main(String args[]) < JBT obj = new JBT(); obj.method(20); obj.method(); >void method(int variable) < variable = 10; System.out.println("Value of Instance variable :" + this.variable); System.out.println("Value of Local variable :" + variable); >void method() < int variable = 40; System.out.println("Value of Instance variable :" + this.variable); System.out.println("Value of Local variable :" + variable); >>
The output of the above program
Value of Instance variable :5 Value of Local variable :10 Value of Instance variable :5 Value of Local variable :40
this Keyword with Constructor
“this” keyword can be used inside the constructor to call another overloaded constructor in the same class. It is called the Explicit Constructor Invocation. This occurs if a Class has two overloaded constructors, one without argument and another with the argument. Then “this” keyword can call the constructor with an argument from the constructor without argument. This is required as the constructor cannot be called explicitly.
Example of this with Constructor
class JBT < JBT() < this("JBT"); System.out.println("Inside Constructor without parameter"); >JBT(String str) < System.out .println("Inside Constructor with String parameter as " + str); >public static void main(String[] args) < JBT obj = new JBT(); >>
The output of the above program
Inside Constructor with String parameter as JBT Inside Constructor without parameter
As you can see, “this” can invoke an overloaded constructor in the same class.
- this keyword can only be the first statement in Constructor.
- A constructor can have either this or super keyword but not both.
this Keyword with Method
this keyword can also be used inside Methods to call another Method from the same Class.
Example of this keyword with Method
class JBT < public static void main(String[] args) < JBT obj = new JBT(); obj.methodTwo(); >void methodOne() < System.out.println("Inside Method ONE"); >void methodTwo() < System.out.println("Inside Method TWO"); this.methodOne();// same as calling methodOne() >>
The output of the above program
Inside Method TWO Inside Method ONE
Example of this keyword as a Method parameter
public class JBTThisAsParameter < public static void main(String[] args) < JBT1 obj = new JBT1(); obj.i = 10; obj.method(); >> class JBT1 extends JBTThisAsParameter < int i; void method() < method1(this); >void method1(JBT1 t) < System.out.println(t.i); >>
If you understood this keyword correctly, the next step should be to understand the Static Keyword in Java from Java Tutorial.
References
1- Official Document
Next Post
Java Static Keyword
70 thoughts on “this keyword in Java”
class car
int speed;
car()
speed=70;
>
protected void finalize()
System .out.println(“destroy object of car”);
>
>
class bike
int speed;
bike()
speed=70;
>
protected void finalize()
System.out.println(“destroy object of bike”)
>
>
class Garbage_Collection
public static void main(String []args)
car c=new car();
bike b=new bike();
b=null;
System.gc();
System.out.println(“speed of car: “+c.speed);
>
>
class JBT <
public static void main(String[] args) <
JBT obj = new JBT();
obj.methodTwo();
>
void methodOne() <
System.out.println(“Inside Method ONE”);
>
void methodTwo() <
System.out.println(“Inside Method TWO”);
this.methodOne();// same as calling methodOne()
>
> when I removed ‘this’ from the line this.methodOne();// same as calling methodOne() I get the same output. Is this the standard behaviour ?
Yes, that is standard behavior. this is just used to point to the current object and in this case, it is the current object’s method. So it will get called.
Using the this Keyword
Within an instance method or a constructor, this is a reference to the current object 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 .
Using this with a Field
The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.
For example, the Point class was written like this
but it could have been written like this:
Each argument to the constructor shadows one of the object’s fields inside the constructor x is a local copy of the constructor’s first argument. To refer to the Point field x , the constructor must use this.x .
Using this with a Constructor
From within a constructor, you can also use the this keyword to call another constructor in the same class. Doing so is called an explicit constructor invocation. Here’s another Rectangle class, with a different implementation from the one in the Objects section.
public class Rectangle < private int x, y; private int width, height; public Rectangle() < this(0, 0, 1, 1); > public Rectangle(int width, int height) < this(0, 0, width, height); > public Rectangle(int x, int y, int width, int height) < this.x = x; this.y = y; this.width = width; this.height = height; >. >
This class contains a set of constructors. Each constructor initializes some or all of the rectangle’s member variables. The constructors provide a default value for any member variable whose initial value is not provided by an argument. For example, the no-argument constructor creates a 1×1 Rectangle at coordinates 0,0. The two-argument constructor calls the four-argument constructor, passing in the width and height but always using the 0,0 coordinates. As before, the compiler determines which constructor to call, based on the number and the type of arguments.
If present, the invocation of another constructor must be the first line in the constructor.
this Keyword in Java: What is & How to use with Example
this keyword in Java is a reference variable that refers to the current object of a method or a constructor. The main purpose of using this keyword in Java is to remove the confusion between class attributes and parameters that have same names.
Following are various uses of ‘this’ keyword in Java:
- It can be used to refer instance variable of current class
- It can be used to invoke or initiate current class constructor
- It can be passed as an argument in the method call
- It can be passed as argument in the constructor call
- It can be used to return the current class instance
Click here if the video is not accessible
Understand ‘this’ keyword with an example.
- Class: class Account
- Instance Variable: a and b
- Method Set data: To set the value for a and b.
- Method Show data: To display the values for a and b.
- Main method: where we create an object for Account class and call methods set data and show data.
Let’s compile and run the code
Our expected output for A and B should be initialized to the values 2 and 3 respectively.
But the value is 0, Why? Let investigate.
In the method Set data, the arguments are declared as a and b, while the instance variables are also named as a and b.
During execution, the compiler is confused. Whether “a” on the left side of the assigned operator is the instance variable or the local variable. Hence, it does not set the value of ‘a’ when the method set data is called.
The solution is the “this” keyword
Append both ‘a’ and ‘b’ with the Java this keyword followed by a dot (.) operator.
During code execution when an object calls the method ‘setdata’. The keyword ‘this’ is replaced by the object handler “obj.” (See the image below).
So now the compiler knows,
- The ‘a’ on the left-hand side is an Instance variable.
- Whereas the ‘a’ on right-hand side is a local variable
The variables are initialized correctly, and the expected output is shown.
Suppose you are smart enough to choose different names for your instance variable and methods arguments.
But this time around, you create two objects of the class, each calling the set data method.
How the compiler will determine whether it is supposed to work on instance variable of object 1 or object 2.
Well, the compiler implicitly appends the instance variable with “this” keyword (image below).
Such that when object 1 is calling the set data method, an instance variable is appended by its reference variable.
While object 2 is calling the set data method, an instance variable of object 2 is modified.
This process is taken care by the compiler itself. You don’t have to append ‘this’ keyword explicitly unless there is an exceptional situation as in our example.
Example: To learn the use “this” keyword
Step 1) Copy the following code into a notepad.
this keyword in java with example
this keyword in java is used to refer to current object or instance of class. It can be used in the constructor to call any other overloaded constructor but this keyword should be the first statement in the constructor.
This keyword can be used for instance variables
this keyword can be used to refer to the instance variable of class.
When you run above program, you will get below output:
As you can see we have used this keyword to set values for instance variable in the constructor.
This keyword can be used to call the overloaded constructor
If you want to call overloaded constructor of same class, you can use this keyword to do that.
For example:
When you run above program, you will get below output:
Calling No arg constructor
Calling Parameterized constructor
Employee’s name : John
Employee’s age : 20
Please note that this keyword used for calling another constructor should be first statement in that constructor.
this keyword can be used return object of the class
that’s all about this keyword in java.
Related posts
How to Get Variable From Another Class in Java
Increment for Loop by 2 in Java
Return ArrayList in Java
Check if Object Is Null in Java
How to Print Multiple Variables in Java
What is == in java
Multiple classes in one file in Java
How to break out of nested loops in Java
public static void main(String[] args) – Java main method
Top 20 Java Projects for Beginners
Was this post helpful?
Share this
Related Posts
Author
Related Posts
How to Get Variable From Another Class in Java
Table of ContentsClasses and Objects in JavaAccess Modifiers in JavaGet Variable From Another Class in JavaUsing the Default or Public Access Modifier of the Other ClassUsing the Static Member of Another ClassUsing the Inheritance Concept of JavaUsing the Getters and Setters of Another ClassUsing the Singleton Pattern Design for Declaring Global VariablesConclusion In this article, […]
Increment for Loop by 2 in Java
Table of ContentsHow to increment for loop by 2 in JavaHow to increment for loop by n in Java In this post, we will see how to increment for loop by 2 in Java. There are several looping statements available in Java and one of them is for loop in java. There are three parts […]
Return ArrayList in Java
Table of ContentsReturn ArrayList in Java From a Static MethodReturn ArrayList in Java From a Non-static MethodConclusion This article discusses cases of returning an ArrayList in Java from a method. An ArrayList in Java is a collection of elements of the same data type under a single variable name. In different cases, you can return […]
Check if Object Is Null in Java
Table of ContentsComparison Operator to Check if Object Is Null in JavaisNull() Method to Check if Object Is Null in JavanonNull() Method to Check if Object Is Null in JavarequireNonNull() Method to Check if Object Is Null in JavaConclusion An object in Java is an instance of a class. It is a real entity existing […]
How to Print Multiple Variables in Java
Table of ContentsWays to Print Multiple Variables in JavaUsing System.out.printUsing System.out.printfPrint Multiple Variables in Java Using LoggerFrequently Asked QuestionsHow Do I Print Multiple Values on One Line in JavaHow to Print Multiple Integers in JavaHow to Print String and Integer in Same Line in Java In this post, we will see how to print multiple […]
What is == in java
Table of ContentsWhat is meaning of == in JavaCode example of ==Object equality using equal to ==The difference between == and equals== in EnumConclusion In this tutorial, we will learn what is == in Java as it is a common lexeme that we will use while developing applications. The == lexeme can be confused with […]