0
color = c; instead of this.color = c;
An example for a constructor in the course is this: public class Vehicle { private String color; Vehicle(String c) { color = c; } } Why doesn't it say ... this.color = c; ... instead of ... color = c; ... as color is always referring to an attribute of the very class?
1 Antwort
+ 1
The compiler will assign "this" object automatically if not referred to. It is good practice to always use this so another programmer that reads your code can easily know that you refer to the class object. Actually, the problem can be if you put same name in your constructor (or any other method) parameter as your variable that you MUST explicitly say assign that value to "this" value:
public class Vehicle {
private String color;
Vehicle(String color) {
this.color = c; // with no this reference your class field won't be changed (in
this case will remain null
}
}