First, the basic concept
1. The keyword this refers to: which object calls the function where this is located. This will point to the current object.
2. Usage:
(1). The This keyword resolves: privatization of constructors.
Note: Constructors can only be called by constructors and cannot be called directly by a generic method.
(2). The This keyword can be used for calls between constructors, and other constructors in this class can be accessed. is used to initialize the reuse.
Note: The first line of the constructor must be defined!
Do not appear to call each other, resulting in recursion, easy stack overflow.
(3) the. This keyword is used to differentiate between local variables and member variables with the same name.
Note: The This keyword identifies the member variable.
Second, the code example
classperson{PrivateString name; Private intAge ; Person () {name= "Bady"; } person (String N) {name=N; } person (String name,intAge ) { This(name);//call the constructor statement. This. Age = Age;//This identifies the member variable. } Public voidShow1 () {System.out.println ("Name=" +name); } Public voidShow2 () {System.out.println ("Name=" +name+ ", age" +Age ); } //pass a Person object to determine whether they are peers. Public Booleanequalsage (person pp) {returnPp.age = = This. Age; }}classthisdemo{ Public Static voidMain (string[] args) {person P1=NewPerson (); P1.show1 (); Person P2=NewPerson ("Xiaoming"); P2.show1 (); Person P3=NewPerson ("xiaoming", 20); P3.show2 (); Person P4=NewPerson ("Xiaohong", 21); P4.show2 (); //call the Equalsage method to determine if P3 and P4 are peers. Booleanb =P3.equalsage (p4); System.out.println (' Whether or not ' is equal: ' +b); } }
Third, the code to run
Java Object-oriented keyword This getting started instance