Keyword this in Java

The “this keyword” in Java refer to the the current object (current instance). All your instance variables may be referred as 'this.variableName' even though it is implicit in most cases. 

The “this keyword”  is mostly useful in below cases:

  1. Refer to instance variables of a class when a local variable has precedence over it.

    • A local variable with same name as the instance variable will take precedence over the instance variable in the local variable’s scope. We can use this keyword in such cases to refer to the instance variable. A major use of this approach comes in the setter methods.

  2. We can call one constructor from another constructor using this().

    • Similar to methods, we can overload constructors i.e. we can have more than one constructor with same name and but different parameter set. Note that constructor names for a class are always same as it is the class name itself.

    • Java won’t allow us to create an infinite loop by calling one constructor from another and then the other calling it back. Compilation will fail because of “Recursive constructor invocation”.

    • Similarly you may call a super class constructor using super() keyword (we will discuss about super later.)

  3. To refer to the current object and pass it to a method or return it from a method

    • Someone might want to get the reference to the current object.

    • You may also register yourself (current object) as a listener in some callback register.

 

Important Note

  1. Since this object represent the current object in question (whichever object user created using new), it cannot be used from a static context. 

    1. However, we can refer to a static variable using a this pointer (from an instance context.)

 

Examples

Example: Refering to instance variables of a class when a local variable has precedence over it.

class MyClass{

 int myVar=5;

 public void setMyVar(int myVar)

 {

   this.myVar = myVar;

 }

}

 

Example: Calling one constructor from another constructor using this().

 class MyClass{

 int myVar=5;

 public void setMyVar(int myVar)

 {

   this.myVar = myVar;

 }

}

 

Example 3: Refering to the current object and pass it to a method or return it from a method.

We can invoke a method with signature myMethod(MyClass c) from MyClass as:

myMethod(this);

We can return the current object from a method with return type MyClass from MyClass as:

public MyClass getInstance()

{

...

return this;

}

Comments

please explain this keyword in more detail. if one class have 2 object . then "this" keyword refer whom and in case of parent and child class use of "this" keyword refer whom super or child class or object.

Was it useful?

this will refer to current object or instance.

if you have an instance variable, then every object created will have its own copy of the instance variable. Similarly there will be different copy of this object. 

if there are three objects, there will be three instance varialbe copies and three this copies. 

this is mainly used to differentiate between an instance and local variable with same name as in example 1. it is also used for calling another constructor.

for calling super class constructor, you use another keyword super.

Was it useful?

Use 3: To refer to the current object and pass it to a method or return it from a method.

need example for this 

Was it useful?

How does "this" behave in static context .  I mean if There is a static block, and a non static method, can a static method call other non-static methods in the same class by using the 'this' , and also is vice versa possible?

Was it useful?

"this" refer to the current object. It will be different for each object that you create. If you refer to "this" from a static block or method, then Java will not be able to decide which of the objects to call. So you cannot call this from static context. In simple, you cannot call or access anything belonging to instance context from a static context.  

Was it useful?

Quick Notes Finder Tags

Activities (1) advanced java (1) agile (3) App Servers (6) archived notes (2) Arrays (1) Best Practices (12) Best Practices (Design) (3) Best Practices (Java) (7) Best Practices (Java EE) (1) BigData (3) Chars & Encodings (6) coding problems (2) Collections (15) contests (3) Core Java (All) (55) course plan (2) Database (12) Design patterns (8) dev tools (3) downloads (2) eclipse (9) Essentials (1) examples (14) Exception (1) Exceptions (4) Exercise (1) exercises (6) Getting Started (18) Groovy (2) hadoop (4) hibernate (77) hibernate interview questions (6) History (1) Hot book (5) http monitoring (2) Inheritance (4) intellij (1) java 8 notes (4) Java 9 (1) Java Concepts (7) Java Core (9) java ee exercises (1) java ee interview questions (2) Java Elements (16) Java Environment (1) Java Features (4) java interview points (4) java interview questions (4) javajee initiatives (1) javajee thoughts (3) Java Performance (6) Java Programmer 1 (11) Java Programmer 2 (7) Javascript Frameworks (1) Java SE Professional (1) JPA 1 - Module (6) JPA 1 - Modules (1) JSP (1) Legacy Java (1) linked list (3) maven (1) Multithreading (16) NFR (1) No SQL (1) Object Oriented (9) OCPJP (4) OCPWCD (1) OOAD (3) Operators (4) Overloading (2) Overriding (2) Overviews (1) policies (1) programming (1) Quartz Scheduler (1) Quizzes (17) RabbitMQ (1) references (2) restful web service (3) Searching (1) security (10) Servlets (8) Servlets and JSP (31) Site Usage Guidelines (1) Sorting (1) source code management (1) spring (4) spring boot (3) Spring Examples (1) Spring Features (1) spring jpa (1) Stack (1) Streams & IO (3) Strings (11) SW Developer Tools (2) testing (1) troubleshooting (1) user interface (1) vxml (8) web services (1) Web Technologies (1) Web Technology Books (1) youtube (1)