Java Object-oriented keyword This getting started instance

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.