-1

Simple question that I couldn't find an answer to online, I created a GUI class that extends JFrame and in the constructor I create the Frame using "setSize(10,10);" and so on, however, many online examples use "this.setSize(10,10);" so my question is; is there any difference at all in the following:

setSize(10,10);
this.setSize(10,10);
  • 2
    no difference, but IMO the second line is more maintainable/readable than the first line. – mre Jun 08 '18 at 17:16
  • Note that referring to a variable is a different story - if there is a local variable `foo` and instance variable `foo`, then `foo` will refer to the local variable while `this.foo` will refer to the instance variable. If there is no local variable, `foo` will refer to the instance variable. – Jiri Tousek Jun 08 '18 at 17:20

2 Answers2

2

If you don't use this keyword before members of the class, it will be added automatically while compiling. So, referring to any member of the class from some function (like constructor) can be done without this keyword if the function you are at doesn't have the argument with the same name as the member. But if it does then you would have to use this to refer to the class member variable instead of parameter.

wdc
  • 2,623
  • 1
  • 28
  • 41
  • 2
    what if it wasn't in the constructor of the class? – Ousmane D. Jun 08 '18 at 17:22
  • @Aominè Same, it could be in any function of the class, `this` is automatically added while compiling, as aman5319 said. – wdc Jun 08 '18 at 17:27
  • 1
    Well, your answer suggests that it's only the same if `this` is used in the constructor. can you update your answer to remove this ambiguity please ;-) – Ousmane D. Jun 08 '18 at 17:28
0

No there is no difference when you call your method like this

setSize(10,10);

during compilation java compiler automatically converts it into

this.setSize(10,10);
aman5319
  • 662
  • 5
  • 16