7

I was studying method overriding in Java when ai came across the this keyword. After searching much about this on the Internet and other sources, I concluded that thethis keyword is used when the name of an instance variables is same to the constructor function parameters. Am I right or wrong?

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
Junior Bill gates
  • 1,858
  • 4
  • 20
  • 33
  • 4
    Not always. There can be several cases. For example, when you want to pass your own instance to a method as a parameter, you do `method(this)`. – Tae-Sung Shin Jan 03 '12 at 05:20
  • 1
    @Junior Bill gates: That's just one valid use of the "this" keyword. – paulsm4 Jan 03 '12 at 05:20

10 Answers10

12

this is an alias or a name for the current instance inside the instance. It is useful for disambiguating instance variables from locals (including parameters), but it can be used by itself to simply refer to member variables and methods, invoke other constructor overloads, or simply to refer to the instance. Some examples of applicable uses (not exhaustive):

class Foo
{
     private int bar; 

     public Foo() {
          this(42); // invoke parameterized constructor
     }

     public Foo(int bar) {
         this.bar = bar; // disambiguate 
     }

     public void frob() {
          this.baz(); // used "just because"
     }

     private void baz() {
          System.out.println("whatever");
     }

}
Anthony Pegram
  • 123,721
  • 27
  • 225
  • 246
  • 3
    Worth pointing out: when used in a constructor, the `this(...)` must be the very first statement. – nneonneo Aug 20 '13 at 03:44
  • 2
    Qualifiers such as `this` or the class name for static calls make your code much more readable and save a lot of time. Within a second the reader knows the scope of the variables or methods or its source. I refuse reading/helping with code problems if the appropriate qualifiers werent used. I don't have time to follow the methods or guess in which class they are, especially if modern ide's such as eclipse have autocomplete features on save operations. – djmj Aug 22 '13 at 22:23
10

this keyword can be used for (It cannot be used with static methods):

  1. To get reference of an object through which that method is called within it(instance method).
  2. To avoid field shadowed by a method or constructor parameter.
  3. To invoke constructor of same class.
  4. In case of method overridden, this is used to invoke method of current class.
  5. To make reference to an inner class. e.g ClassName.this
  6. To create an object of inner class e.g enclosingObjectReference.new EnclosedClass
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
2

this keyword have following uses
1.used to refer current class instance variable

 class Student{  
int id;  
String name;  

student(int id,String name){  
this.id = id;  
this.name = name;  
}  
void display(){System.out.println(id+" "+name);}  
public static void main(String args[]){  
Student s1 = new Student(111,"Karan");  
Student s2 = new Student(222,"Aryan");  
s1.display();  
s2.display();  
}  
}  

here parameter and instance variable are same that is why we are using this
2.used to invoke current class constructor

class Student{  
int id;  
String name;  
Student (){System.out.println("default constructor is invoked");}  

Student(int id,String name){  
this ();//it is used to invoked current class constructor.  
this.id = id;  
this.name = name;  
}  
void display(){System.out.println(id+" "+name);}  

public static void main(String args[]){  
Student e1 = new Student(111,"karan");  
Student e2 = new Student(222,"Aryan");  
e1.display();  
e2.display();  
}  
}    

3.this keyword can be used to invoke current class method (implicitly)

4.this can be passed argument in the method call

5.this can be passed argument in the constructor call

6.this can also be used to return the current class instance

murthy naika k
  • 559
  • 6
  • 12
2

You are right, but this is only a usage scenario, not a definition. The this keyword refers to the "current object". It is mostly used so that an object can pass itself as a parameter to a method of another object.

So, for example, if there is an object called Person, and an object called PersonSaver, and you invoke Person.SaveYourself(), then Person might just do the following: PersonSaver.Save( this );

Now, it just so happens that this can also be used to disambiguate between instance data and parameters to the constructor or to methods, if they happen to be identical.

Mike Nakis
  • 56,297
  • 11
  • 110
  • 142
1

Generally the usage of 'this' is reserved for instance variables and methods, not class methods ...

"class methods cannot use the this keyword as there is no instance for this to refer to..."

http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

Here's a trivial example ...

public class Person {
    private String  name;
    private int     age;
    private double  weight;
    private String  height;
    private String  gender;
    private String  race;

    public void setName( String name ) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }

    public void setAge( int age) {
        this.age = age;
    }

    public int getAge(){
        return this.age;
    }

    public void setWeight( double weight) {
        this.weight = weight;
    }

    public double getWeight() {
        return this.weight;
    }

    public void setHeight( String height ) {
        this.height = height;
    }

    public String getHeight() {
        return this.height;
    }

    public void setGender( String gender) {
        this.gender = gender;
    }

    public String getGender() {
        return this.gender;
    }

    public void setRace( String race) {
        this.race = race;
    }

    public String getRace() {
        return this.race;
    }

    public void displayPerson() {
        System.out.println( "This persons name is :"    + this.getName() );
        System.out.println( "This persons age is :"     + this.getAge() );
        System.out.println( "This persons weight is :"  + this.getWeight() );             
        System.out.println( "This persons height is :"  + this.getHeight() );
        System.out.println( "This persons Gender is :"  + this.getGender() );
        System.out.println( "This persons race is :"    + this.getRace() );
    }
}    

And for an instance of a person ....

public class PersonTest {
    public static void main( String... args ) {
        Person me = new Person();
        me.setName( "My Name" );
        me.setAge( 42 );
        me.setWeight( 185.00 );
        me.setHeight( "6'0" );
        me.setGender( "Male" );
        me.setRace( "Caucasian" );
        me.displayPerson();
    }
}
Himanshu Gupta
  • 77
  • 1
  • 1
  • 9
Edward J Beckett
  • 5,061
  • 1
  • 41
  • 41
1

This refers current object. If you have class with variables int A and a method xyz part of the class has int A, just to differentiate which 'A' you are referring, you will use this.A. This is one example case only.

public class Test
{
int a;

public void testMethod(int a)
{
this.a = a;
//Here this.a is variable 'a' of this instance. parameter 'a' is parameter.
}
}
kosa
  • 65,990
  • 13
  • 130
  • 167
0

In case of member variable and local variable name conflict, this key word can be used to refer member variable like,

public Loan(String type, double interest){
this.type = type;
this.interest = interest;
}
user2167728
  • 51
  • 1
  • 5
-1

I would like to modify your language. The this keyword is used when you need to use class global variable in the constructors.

public class demo{
    String name;
    public void setName(String name){
        this.name = name; //This should be first statement of method.
    }
}

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.

One more thing that should be in mind is that this keyword might be the first statement of your method.

Adi Inbar
  • 12,097
  • 13
  • 56
  • 69
Abhendra Singh
  • 1,959
  • 4
  • 26
  • 46
-1

if you have knowladge about c,c++ or pointers, in that language this is a pointer that points object itself. In java everything is reference. So it is reference to itself in java. One of the needs of this keyword is that:

Think that this is your class

public class MyClass
{
      public int myVar;

      public int myMethod(int myVar)
      {
           this.myVar = myVar;        // fields is set by parameter

      }


}

If there is not this keyword you it is confused that this is paramter or class field.When you use this.myVar it refers field of this object.

oldTimes
  • 259
  • 3
  • 4
  • 13
-2

This is used in java. We can use in inheritance & also use in method overloading & method overriding. Because the actual parameter or instance variable name has same name then we can used this keyword complsary . But some times this is not same as when we can not use this keyword complsary..... Eg:- class super { int x; super(int x) { this.x=x } }

G5W
  • 36,531
  • 10
  • 47
  • 80