1. Distinguish between member variables and local variables

If a local variable in a method has the same name as a member variable, the member variable is masked in the method. “Member variable names” specify member variables to distinguish them from local variables:

public class Demo { private int year; private int month; private int day; public Demo(int year,int month,int day){ this.month=month; // use this.month to specify a member variable followed by the parameter this.day=day; this.year=year; } public static void main(String[] args) {Demo d=new Demo(2017,11,20); System. The out. Println (d.y ear + "years" + d.m onth + "month" + d.d ay + ", "); }}Copy the code

2. Call the constructor through this

Usage: tihs(parameter list) This usage is mainly used to reduce duplicate code when an object needs constructors with different parameters to be overloaded for different scenarios. (Note: this can only be used in constructors, not elsewhere.) For example:

public class Demo { private int year; private int month; private int day; public Demo(int month,int day) { this.month=month; this.day=day; } public Demo(int year,int month,int day){ this(month, day); this.year=year; } public static void main(String[] args) {Demo d=new Demo(2017,11,20); System. The out. Println (d.y ear + "years" + d.m onth + "month" + d.d ay + ", "); }}Copy the code

The month and day attributes are already initialized in the first constructor, so they can be called in the second constructor to avoid duplicate code. Instead of this:

public class Demo { private int year; private int month; private int day; public Demo(int month,int day) { this.month=month; this.day=day; } public Demo(int year,int month,int day){ this.month=month; this.day=day; this.year=year; } public static void main(String[] args) {Demo d=new Demo(2017,11,20); System. The out. Println (d.y ear + "years" + d.m onth + "month" + d.d ay + ", "); }}Copy the code

3. When a method needs to reference the current object of the method’s class, use this

In the following example: in the show() method, the member variable year of the current class object D is referenced by “this.year”.

public class Demo { private int year; private int month; private int day; public Demo(int year, int month, int day) { this.month = month; this.day = day; this.year = year; } public void show() {system.out.println (this.year + "" + this.month +" "+ this.day + "); } public static void main(String[] args) { Demo d = new Demo(2017, 11, 20); d.show(); }}Copy the code