Use Java this keyword

this keyword indicates that the object itself.

this keyword is primarily for use in the following three cases:

1. solve the problem of local variables and member variables of the same name;

2. problem solving method parameters and member variable of the same name;

3. to call another class constructor.

Special attention: Java language requirements, this key can only be used in non-static method (instance methods and constructor), can not be used in static methods.

First, local variables and member variables of the same name, then the local variable hides the member variable

public Employee(String name, int age, double salary) {
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

Second, the method parameters and member variable of the same name

public void setName(String name) {
        this.name = name;
    }

Third, for calling another class constructor

 public Employee() {
        this("李明",25,3000);

    }

Note: provided that: a constructor call another constructor in the same class.

   If you call another constructor in the constructor, then this statement must be the first statement.

Guess you like

Origin www.cnblogs.com/my-program-life/p/11011944.html