-1

Can someone explain me what is the difference between those two codes? When I have to use first and when second? It is clear that when method has parameter with the same name as data member in the class, I have to use "this". But here method dont have any parameters. When in this case I have to use "this"?

public float getPrice(){
    return this.price;
}     


public float getPrice(){
    return price;
}
Ana Matijanovic
  • 277
  • 3
  • 13
  • 2
    You don't have to use `this` here. Since (I assume) `price` is an instance variable and there's no name conflicts – Andrew Li Apr 11 '17 at 20:37
  • You don't have to use `this`. It may just make the code clearer, especially if you normally prefix member variables with `this`. – Robert Apr 11 '17 at 20:38
  • Read [this](http://stackoverflow.com/questions/23250/when-do-you-use-the-this-keyword). Pun intended :) – Brian Apr 11 '17 at 20:38
  • `this` uses the current enclosing instance as scope explicitely. nothing uses any scope in order, starting from the most specific. – njzk2 Apr 11 '17 at 20:39
  • (yes the dup is C#. but the answer applies just as well to _this_ question) – njzk2 Apr 11 '17 at 20:40
  • http://stackoverflow.com/questions/2411270/when-should-i-use-this-in-a-class The thing that confuses me, is this question. Best answer with 2. example of using "this"? Why in that code he used "this"? Just to make it clearer or there is another reason? – Ana Matijanovic Apr 11 '17 at 20:40
  • @AnaMatijanovic I was looking for this :p –  Apr 11 '17 at 20:41

1 Answers1

1

this designates the instance of the class. So you can always use it if you are accessing a member.

this isn't necessary if, in the expression, this.x, there is only 1 x in scope.

If there are two x's in scope, as in the example below, you can use this to indicate which you really mean.

public class C{
private int x;  

public void f(int x){
   x = 5;  // this sets the parameter to 5
   this.x = 6; // this sets the instance member x to 6; 
}
Rob Gorman
  • 3,502
  • 5
  • 28
  • 45
  • So if method has no parameters, there is no reason to use "this"? Cause no matter which instance variable I have, it will never exist two the same variables? Can you please check link in my comment and answer on my question? – Ana Matijanovic Apr 11 '17 at 20:44
  • Well, the method could also have some local variables with names that are the same as the names of some fields. However, it's good practice always to give local variables different names from your fields. @AnaMatijanovic – Dawood ibn Kareem Apr 11 '17 at 21:02