Java Object-oriented programming (III)--this

Source: Internet
Author: User

Look at a piece of code: (Demo112.java), first understand why you want to use this.

/*the necessity of this*/ Public classdemo112{ Public Static voidMain (String []args) {Dog dog1=NewDog (2, "rhubarb"); Person P1=NewPerson (dog1,23, "just son"); Person P2=NewPerson (dog1,24, "Dragons");            P1.showinfo ();    P1.dog.showInfo (); }}//Define a humanclassperson{//member Variables    intAge ;    String name; Dog Dog; // Reference type 
// Human tectonic functions     Public Person (dog dog,int  age,string name) {        //This writing is poorly readable and does not know which of the two age refers to the parameter list, which refers to the member variable.          // age=age;         // Name=name;
//introduce this to point to the current object.          This. age=age;//this.age Specifies the member variable age         This. name=name;//this.name Specifies the member variable name         This. dog=Dog; }    //Show person Name     Public voidShowinfo () {System.out.println ("Name is:" + This. Name); }}classdog{intAge ;    String name;  PublicDog (intage,string name) {         This. age=Age ;  This. name=name; }    //Show Dog name     Public voidShowinfo () {System.out.println ("Dog name" + This. Name); }}

The

shows from the case that introducing thsi is necessary. This is an object that is not part of a class, but it cannot be used outside of the class definition and can only be used in methods defined by the class . The Java virtual Opportunity assigns this to each object, representing the current object.

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.