Is someone able to explain why name = this.name not work?
Why does name = this.name not work?
Under discussion
Comments (3)
- Popular
- New
- Old
You must be signed in to leave a comment
Anonymous #11263139
10 February, 14:09
When you write:
this.name =name
If you change the name of the variable:
private String change = "nameless cat"; public void setName(String other) {
this.change = other;
0
Anonymous #11263139
10 February, 06:38
private String name = "nameless cat";
public void setName(String name) {
name = this.name;
}
In other words:
this.name = nameless cat
name =it is the value that you pass to the method
If you change the name of the variable:
private String change = "nameless cat";
public void setName(String other) {
other = this.change;
.....
System.out.println(cat.change);
One is a local variable (other) and the (change) is an instance variable.
Remember:
If the local variable that is received has the same name as the instance variable, the - this - is used.
So
this.name = name;
instance variable = local variable
this.name is :
private String name = "nameless cat";
name is:
The local variable
We pass the value to the local variable and assign it to the instance variable
cat.setName("Simba");
this.name = Simba
0
Misiu
29 March 2020, 20:31
this.name = name; works
+2