Java member variables have the same name as local variables, and java member variables have the same name.
When I saw the same name of a member variable and a local variable, it was a little difficult at first.
Let's look at a simple code.
First, I define a Person class.
Public class Person {private int age = 1000; // defines the member variable. The age is 1000 public void setAge (int age) {age = age; System. out. println ("age in the method" + age);} public void sayHello () {System. out. println ("My age is" + age + ". ");}}
Then, create an object in the main function and output it.
Person p=new Person();p.setAge(20);p.sayHello();
What is the output result? We don't think my age is 20, but below:
// The Age in the method is 20 // my age is 1000.
It is easy to understand.
In a word, if the name is different, the variable name in the method represents the member variable; if the name is the same, the variable name in the method only represents the local variable, and there is no relation to the member variable.
Therefore, when we create a Person object p, the initialization of the member variable is completed when the object is created. The initial value of the member variable age is 1000.
When we p. in setAge (20), in fact, this 20 only works in the setAge method, so the age 20 in the method is output. After this sentence is executed, 20 is destroyed.
Then execute sayHello. The age in it represents the value of the member variable, so it is still 1000.
If you still cannot understand it here, you can write your own code to view the output result.
So when the same name is used, is there a way to make the variable name represent the member variable?
This keyword is required. We changed the Person class to the following:
Public class Person {private int age = 1000; public void setAge (int age) {this. age = age; System. out. println ("age in the method" + age);} public void sayHello () {System. out. println ("My age is" + age + ". ");}}
Run the code again and find that the code running result is as follows:
// The Age in the method is 20 // my age is 20.
This indicates the current object.
This. age indicates that the age of the p object (that is, the age of the p object member variable) is 20.
If you cannot understand it, you can simply write more code to understand it.