Java this keyword

Source: Internet
Author: User

The this statement can only be used between constructors and cannot be used in general functions.

This keyword: appears to be used to differentiate between member variables and local variables with the same name.
(1) If the member variable and the local variable have the same name, only the member variable is recognized in the function.
This: it represents the object of this class, but which one does it represent?
This represents the reference to the object to which the function belongs.
Simply put: Which object is the object that represents the function that this is located in.

This keyword applies: When you define a function in a class, it is used internally to represent the object when the function is called.
This type of object is used internally by this function and is represented by this.
**********************************************
(2) This "statement": Used to call each other between constructors.

The this statement can only be defined in the first row of the constructor, based on the following: initialization and then changing the value of the variable. Because initialization is performed first.
Class Person {private String name;private int age; Person (String name) {this.name=name;} Person (String Name,int age) {This (name);////////////With this statement instead of This.name=name, in fact this (name) is called the previous constructor; This.age=age;} public void Show () {System.out.println ("Name:" +name+ ", Age:" +age);} Compare two people who are of the same age public boolean compare (person p) {return this.age==p.age;}} Class Persondemo3{public static void Main (string[] args) {person p1=new person ("Zhangsan"); Person P2=new person ("Lisi", 34); Person P3=new person ("Wangwu"), Boolean flag=p2.compare (P3), if (flag) {System.out.println ("yes");} Else{system.out.println ("No");} P1.show ();//p2.show ();}}

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.