0

Say you have a constructor which initializes a field.

private int world;

public Hello(){
  world = 5;
}

Now, take this variant:

private int world;

public Hello(){
  this.world = 7;
}

Is there a difference with the latter? The only reason I would know to use "this" in a constructor, or any method, is to specify a field is a field and not a parameter argument by indicating it to be a call from "this" current object. Would it matter if I used it without the aforementioned case?

  • 1
    For beginners, it's often encouraged to use `this.`... For some platforms, naming a *member variable* `mWorld` is encouraged. However, in this case, there is no difference – OneCricketeer Apr 08 '18 at 17:09
  • No difference in this context. "this" is used to explicitly point to member variable. It is useful if a local variable has the same name as member variable. The former would shadow the member variable. Some reading: https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html – Witold Kaczurba Apr 08 '18 at 17:15

1 Answers1

0

In the case you provided, it is the same.

In the following case, this. does matter:

private int world;

public Hello(int world){
  this.world = world;
}
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443