Java Learning Note III: this usage

Source: Internet
Author: User

In general, when we refer to other classes externally, we need to declare this type reference, such as

New Thisdemo ();

There is an example of this in "Java Programming ideas":

Newnew  Banana ();        A.peel (1); B.peel (2);

When we declare an object reference, we usually use the above method, but the compiler does some work, the actual result is:

It secretly passes the reference of the Manipulated object as the first parameter.

12);

But if we want to use the current class's reference inside the current class, this keyword will be used.

This method of use:

The This keyword means that a reference to the "object calling the method" is actually a reference to the object of the current class.

1. Distinguish between data member variables and parameter variables, typically used in the get and set methods.

classthisdemo{PrivateString name; Private intAge ; /** * @return the name*/     PublicString GetName () {returnname; }        /** * @param name the name to set*/     Public voidsetName (String name) { This. Name =name; }        /** * @return The Age*/     Public intGetage () {returnAge ; }        /** * @param Age-The age-to set*/     Public voidSetage (intAge ) {         This. Age =Age ; }}

2. Return a reference to the current object

Satisfies that multiple operations are performed on the same object in a single statement.

Here is an example of "Java Programming idea":

classleaf{inti =0;  PublicLeaf Increment () {i++; return  This;//returns a reference to the leaf of the current object    }        Public voidprint () {System. out. println (i); }         Public Static voidMain (string[] args) {leaf leaf=NewLeaf ();     Leaf.increment (). Increment (). Increment (). Increment (). print (); }}

The output is: 4.  The reasons for this increase are: the leaf leaf = new leaf (); At initialization i = 0, when the call method increment () returns the Leaf reference, I is not initialized again, but the value after i++ is used.

3. Pass a reference to the current object to another method.

Example or using the "Java Programming idea", here is a description of the following scenario:

(1) The user wants to eat apples, and provides a complete apple to other people (here "other people" we can understand as a processing plant, deeper can be understood as a third-party jar, tools, etc.);

(2) The user does not care about the processing method, as long as can return to a peeled apple, as for "other people" in what methods, tools, users do not care.

/** * User class*/classperson{ Public voideat (Apple apple) {//the user only cares about getting peeled apples//Apple Apple is a complete apple with no peelingApple peeled =Apple.getpeel (); }}/** * Apple class*/classapple{ PublicApple Getpeel () {//pass the Apple to Peeler        returnPeeler.peel ( This); }}/** Peel Operation * This is only used for static, usually the tool*/classpeeler{ Public StaticApple Peel (Apple apple) {//TODO peeling operation, return a peeled apple        returnApple; }}

1). For person, Peeler is not visible, and Peeler do what we are not visible. At the same time, users are concerned.

2). The use of this in the Peel method is used in the pass to Peeler.

Example two:

Scenario: We need to assemble a device (such as a mobile phone), need to use different components, if multiple product lines at the same time, how to know that no duplicate components installed on the same device (a mobile phone loaded with two batteries?) )

/** * Mobile phone*/classphone{PrivateScreen screen ; PrivateBattery Battery; /** Assembly Screen*/     Public voidAddscreen () { screen=NewScreen ( This); }        /** * Assembled battery*/     Public voidaddbattery () {Battery=NewBattery ( This); }}/** * Screen*/classscreen{PrivatePhone p;  PublicScreen (phone phone) {//TODO Assembly Screenp =phone; }}/** * Battery*/classbattery{PrivatePhone p;  PublicBattery (Phone phone) {//TODO Assembly Screenp =phone; }}

Use this to set the current phone to the component that needs to be installed, and pass the phone reference to the other components.

PS: Realistic scene, easy to understand: to the seafood market to buy seafood, and then to the nearby restaurants for processing, passed to the restaurant seafood is this.

4. Calling other constructors in the constructor

If there are multiple constructors in a class, and a constructor has other constructors that want to invoke the current class, you can use this.

Attention:

1. One of the constructors can not be used to whine two other constructors;

2. The constructor must be placed in its place of fact.

//----------------Method 4--------------classthissstructure{ PublicThissstructure (inti) {System. out. println (i); }         PublicThissstructure (Stringstring) {System. out. println (string); }         PublicThissstructure (intI, Stringstring)    {         This(i);//call the first constructor, you must put that at the very beginning//This (STIRNG);//compile an error, cannot use two simultaneously    }         Public Static voidMain (string[] args) {thissstructure ts=NewThissstructure (1,"Test"); }}

Summarize:

This represents a reference to the current object, as long as you keep this feature in mind and pay attention when you use it.

Java Learning Note III: this usage

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.