+ 4
hello! can anyone explain the keyword this please I didn't understand it
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.
+ 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. :)
- 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