+ 4

hello! can anyone explain the keyword this please I didn't understand it

24th Feb 2016, 8:21 PM
Kaoutar Noureddine
Kaoutar Noureddine - avatar
3 Answers
+ 21
lets say we have this code: class Animal{ private int height; private String name; private String Color; Animal(int height,String name,String Colour){ this.height=height; this.name=name; Color=Colour; } } As you can see inside the constructor instead of Color i wrote Colour. The compiler understands that variable "Colour" refers to constructor variable and variable "Color" refers to our object variable ...so its not neccesary to write "this.Color=Colour". On the other hand the constructor variables "name" and "height" have the same name with the object variables so the compiler doesnt know which variable you are refering to. For that reason we must use keyword "this" (Imagine if we wrote only "height=height". That would cause compile error). "This" keyword refers to the object variable such as objects methods.
4th Mar 2016, 7:19 PM
Xristos
Xristos - avatar
+ 11
The keyword "this" basically means that we are referring to the current object. If I made a Car class, I can have a Honda and Toyota. Whatever variables or methods that I am working with would only refer to either the Honda or Toyota by using "this". Example: Inside the Honda object: this.color = "blue"; //The Honda car is blue Inside the Toyota object: this.color = "red"; //The Toyota car is red "this" is awesome because we can reuse the same variable names for different objects. Hope this helps. :)
24th Jun 2016, 12:48 AM
Scylla
Scylla - avatar
- 1
see its very simpal this is a keyword that makes the value of a variable constant I.e if you will do any calculation or anything and check the value of the variable in which you have used this keyword the value remains the same as befour
5th Aug 2016, 11:13 AM
Aditya
Aditya - avatar