0
It works without this too
Please explain when the use of this will get usefull. In the program given, I dont find a difference between color =c and this. color=c Please help me understand.
2 odpowiedzi
+ 2
The "this" keyword referrs to the current instance of the class.
In most cases it is not neccessary, but still can be preferred as it tells you that you're using an instance variable.
Whether or not you use it is more of a preference thing, I personally prefer it if I don't have an IDE that changes the color of instance variables.
In other cases, it could be mandatory.
For example, returning and comparing the current object instance.
class ex{
public ex isSub(){
if (this instanceOf sub)
return this;
return null;
}
}
class sub extends ex{}
Here I created a method that will only return the object if it's an instance of a certain class.
+ 1
this is redundant most of the time but when you have two variables of the same name, one local and one instance, then keyword "this" is used to denote the instance variable. in IDE like eclipse, "this" is very useful for using IDE auto completion features.
you can also use "the" to call on a member methods by just passing in parameter variables. complier is smart enough to figure out what function you are calling.