Advertisement



< Prev
Next >



Java this Keyword





Have you ever thought about how to access the currently executing object of a class in Java? Don't worry if you don't know about it, because we will discuss just that and a lot more relevant in this tutorial.

Let us explain each of the above-described uses of this keyword with examples.





To use this keyword to access a currently executing object and its instance variables, to resolve the shadowing issue.

// Example of this keyword in Java

class A
{
int a;

public void putValue(int a)
{
	//Accessing an instance variable with this keyword, to differ it from a local variable with same name
	this.a=a; 
}


public static void main(String... ar)
{
	A ob = new A();
	ob.putValue(10);
	System.out.println("Value in a : "+ ob.a);
}
}


Output-


Value in a : 10

In the putValue() method, we have accessed an instance variable named a with this keyword, which has distinguished its name from a local variable named a to resolve the shadowing issue.



Please share this article -





< Prev
Next >
< Static Keyword
Encapsulation >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement