0

Whta ia the use of this in setter method. I get the same output witjout use of this keyword.

public void setColor(String c) { this.color = c; } public void setColor(String c) { color = c; } how the above two are different?

9th Sep 2017, 9:26 AM
naveen
6 odpowiedzi
+ 6
1. It prevents shadowing (if you created a global variable named c you might use the argument c although you want to use the global variable). 2. Usually you will name the parameters of a constructor exactly like the attribute. Then you need to use this to tell the compiler what variable you want to use, example: class MyClass { String s; public MyClass(String s) { this.s=s; } }
9th Sep 2017, 9:40 AM
Tashi N
Tashi N - avatar
+ 4
There is no difference in your examples, because you named the parameter of the setter method not the same as the attribute. But it's a best practice to do so. So you name the parameter of your setter method color and use this.color=color; in the methods body. It's not a must, but setter methods are commonly written like that.
9th Sep 2017, 9:50 AM
Tashi N
Tashi N - avatar
+ 1
thank you. very much helpful
9th Sep 2017, 9:53 AM
naveen
0
then is it like this keyword is necessary when it is constructor and not in setter?
9th Sep 2017, 9:43 AM
naveen
0
public class Vehicle { private String color; // Getter public String getColor() { return color; } // Setter public void setColor(String c) { color = c; } } class Program { public static void main(String[ ] args) { Vehicle v1 = new Vehicle(); v1.setColor("Red");Vehicle v2 = new Vehicle(); v2.setColor ("Blue"); System.out.println(v1.getColor()); System.out.println(v2.getColor()); } } this program gives me the same result when i assign the color attribute like this.color=c;
9th Sep 2017, 9:45 AM
naveen
0
may i know how execution is different in these two scenarios?
9th Sep 2017, 9:45 AM
naveen