+ 1

Should a SETTER always have "this" keyword? Or can it even work without it?

class Animal { private int age; void setAge(int x) { age = x; //instead of THIS.AGE = X; /* Wrote the above line in uppercase just to highlight and that's it. No syntax issues */ } int getAge ( ) { return age; } }

25th Jan 2017, 5:47 PM
james nyle
4 Answers
+ 8
Yes, it can work even without this keyword.
25th Jan 2017, 6:26 PM
Saumya
Saumya - avatar
+ 4
You need to use "this" for example, when the object variable and the constructor parameter have the same name: class A { int variable; public A (int variable) { this.variable = variable; } }
25th Jan 2017, 9:45 PM
Jannick
+ 2
To my knowledge, you don't have to use the "this" keyword to set a value, though it's always best to.
25th Jan 2017, 5:49 PM
NickB
NickB - avatar
0
Thanks a lot everyone. :)
26th Jan 2017, 4:59 AM
james nyle