I know that both chunks of code work but as I am trying to understand the use of "this" I would really appreciate it if you could explain me why the class Vehicle1 is 'better' than Vehicle2. Thanks a lot in advance!
public class Vehicle1 { private String color; Vehicle(String c) { this.setVehicle(c); } Vehicle() { this.setVehicle("Red");; } public void setVehicle(String c) { this.color = c; } public String getVehicle() { return color; } } public class Vehicle2 { private String color; Vehicle(String c) { color = c; } Vehicle() { color = "Red"; } public String getVehicle() { return color; } }
this. A constructor shouldn't call an overridable method. Why do you name setVehicle()/getVehicle() methods that set and get the color. Why not setColor()/getColor()?thisis a reference the current Object. You can usethisto do everything you could do with a final variable (you can't assign it), plus (as the first statement in a constructor) invoking another constructor.this.as a method prefix is utterly useless. Your constructors do not chain. You have doubled semicolons. The first example calls an overridable method from a constructor. The constructors are not public. Both examples are crap.