Parameters and this
Module 17's constructors all used lines like this.name = name;, where this.name is the object's variable and name the parameter. The point behind it: a parameter with the same name as an instance variable hides that variable. Inside the constructor or method, a plain name always means the parameter, and this.name is the only way to reach the object's own variable.
Without this
Leave out this., and both sides of name = name; mean the parameter. The line copies the parameter into itself, and the instance variable is never set. It keeps the value every instance variable starts with: 0 for a number, false for a boolean, and null for a String, which means no String at all:
public class Main {
public static void main(String[] args) {
Guest guest = new Guest("Amara", 3);
System.out.println(guest);
}
}public class Guest {
private String name;
private int nights;
public Guest(String name, int nights) {
name = name;
nights = nights;
}
public String toString() {
return this.name + ", " + this.nights + " nights";
}
}null, 0 nightsJava doesn't complain: name = name; is allowed, it just does nothing useful. When an object shows null or 0 where you expected a value, a missing this. is the first thing to look for.
Methods with parameters
The same goes for every method whose parameter has the name of an instance variable. Methods that change an object often get the new value as a parameter:
public class Main {
public static void main(String[] args) {
Guest guest = new Guest("Amara", 3);
guest.extend(2);
guest.rename("Amara Obi");
System.out.println(guest);
}
}public class Guest {
private String name;
private int nights;
public Guest(String name, int nights) {
this.name = name;
this.nights = nights;
}
public void extend(int nights) {
this.nights = this.nights + nights;
}
public void rename(String newName) {
name = newName;
}
public String toString() {
return this.name + ", " + this.nights + " nights";
}
}Amara Obi, 5 nights- In
extend,this.nightsis the guest's nights so far, andnightsis the parameter: the nights to add. - In
renamethe parameter has another name, sonamecan only mean the instance variable, andthis.isn't needed. Many programmers write it anyway, and so does this course: withthis.in front, it's always clear which variables belong to the object.