+ 1
Doubt in Java constructor of using "this" keyword
https://sololearn.com/compiler-playground/c0oQsDiChi9d/?ref=app https://sololearn.com/compiler-playground/cpRQ517jVSJf/?ref=app In the first code I don't use "this" keyword inside constructor method to call setter method In the second code,I use "this" keyword inside constructor method to call setter method.(Which is provided by Sololearn in example) But both return Same results ? I wonder then what is the use of "this" keyword to call setter method
4 ответов
+ 6
in your codes, using or not using 'this' in the getter makes no difference. 'this' is needed only as a specifier to make some statements unambiguous.
In the case of the setter, for example,
// Setter
void setColor(String color) {
color = color;
}
if you used the same word as an argument, and didn't use this.color in the assignment, your setter would not work properly. This would not throw an error, but your color will be null.
+ 4
Hi!
Here's some reading:
https://www.w3schools.com/java/ref_keyword_this.asp
And here's an example from A͢J
https://sololearn.com/compiler-playground/cM8vEGmZj0ja/?ref=app
I think what it all means is that, you might not see the use of it in such a small program, but as your program grows with different uses and inputs etc then you can see the need.
Happy coding!
+ 4
here are two use of this,
- as call constructor from other constructor
- set class variable with same name as local variable
Vehicle(){
this("Blue");
}
Vehicle( String color){
setColor(color);
}
void setColor(String color) {
this.color = color;
}
// in main()
Vehicle v2 = new Vehicle("Red");
System.out.println( v2.getColor() );
+ 4
The this keyword is a way to reference the current object.
Think of it this way: You create a vehicle, let's call it JoesLambo.
If you call, JoesLambo.ride()
Running 'this' inside the ride() method is in reference to the object JoesLambo.
Often the keyword is used for readability, so you know what you're working with like you have come across in the code.
However, it can be used as a more 'necessary' purpose. Here is another use case of 'this' that hasn't been mentioned in other answers:
Imagine you're creating a game.
You have a method in a class called GameState:
public void attackPlayer(Zombie A, Player B)
In which a zombie attacks a player.
Now inside the Zombie class, you have:
Player target; // Instance variable
public void hitSkill()
Where the zombie will 'hit'.
Now you can call the attack method inside hitSkill() with:
myGameStateObj.attackPlayer(this, this.target);
Here I used the keyword 'this' to reference the Zombie that has attacked.