JAVA this keyword

Source: Internet
Author: User

This is an object reference to the current class, and a simple understanding is an object of the current class.

Scenario: Resolve layout variables to hide local variables.

Example:

public class Worker {

Private String Wname;

The first case is as follows:

public void Setwnama (String name) {

Wname=name; This is possible, and The result of the final main function output is Wang, the correct result, because the member variable wname The parameter name of the member function is different from name, and the assignment is valid.

}

The second case is as follows:

public void Setwnama (String wname) {

wname=wname;//The result of this output is null, which is also the default value of type String , indicating that the assignment is invalid. Because the member variable name of the class is the same as the parameter name of the member function, it is not pointed out.

The third case is as follows : Use this to solve the second problem

public void Setwnama (String wname) {

This. wname=wname;// represents the parameter name of the member function assigned to the member variable of the current class object. The result is Wang, which works.

Summary: The first and third methods are effective.

public static void Main (string[] args) {

Worker worker=new Worker ();

Worker.setwnama ("Wang");

System.out.print (worker. Wname);

}

}

JAVA this keyword

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.