The use of my java--this

Source: Internet
Author: User

In a method, you can use a keyword this to represent the object itself. In a normal method, this represents the object that called the method; in the constructor, this represents the newly created object

1. Use this to access the fields and methods of an object

For example: Use name in method SayHello and use THIS.name to be the same;

void SayHello () {

System.out.println ("hello! My name is "+name");

}

And

void SayHello () {

System.out.println ("hello! My name is "+this.name");

}

The meaning is the same.

2. Use this to resolve an issue where the local variable has the same name as the field

You can also use this to resolve problems with local variables (variables in methods) or parameter variables with the same name as field variables. For example, in the construction method, this is often used:

person (int age,string neme) {

This.age=age;

This.name=name;

}

Here, This.age represents a field variable, and age represents a parameter variable.

3. Construct method, call another method of construction with this

Such as:

Person () {

This (0, "");

}

If you call another constructor method in the constructor, the call statement must be placed in the first sentence. (more complex questions about the construction method)

4. Precautions for using this

When using this, be aware that this refers to the invocation of the "object" itself, not the variable or method seen in this class definition.

Attention:

(1) This can not only refer to the domains and methods defined in the class, but also to the domains and methods defined in the parent class of the class.

(2) because it refers to an object, this does not refer to the class variable (static field) through this, and the class method

In fact, in all non-static methods, a parameter this is implied. This is not available in the static method.

The use of my java--this

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.