Java keyword---The origin of this and its three major functions

Source: Internet
Author: User

Huang Zhiping: http://www.cnblogs.com/hzp0619/

Article Source: http://www.cnblogs.com/hzp0619/.html

Body

I am determined to master the Java programming language of a small white, recently I am learning Java Object-oriented three major features (encapsulation, inheritance, polymorphism), often encounter this keyword, but the book is simply a few of the functions of this, I hear is foggy, It doesn't explain why the Java designer created the This keyword, for what reason did you create the This keyword? And what's the problem with this keyword?

These are my doubts, as to why I ask these questions, because I think the learning concept is not only to learn the concept itself, more importantly, to understand and understand the origin of knowledge.

Huang Bo the answer of the Lord:

Hello, everyone! When I first learned this, I only knew what the This keyword did in the program, but I didn't know how the This keyword was generated. This is a good sentence--learning concept not only to learn the concept itself, more important is to understand and understand the origin of knowledge .

You have raised two questions and I have listed the questions:

1.Java Why did the designer create the This keyword, for what reason did you create the This keyword? In short, the This keyword produces a background

2. What problem does this keyword solve? In short, the role of the This keyword

More important is to understand, understand the origin of knowledge "encouragement, I went to the Internet to check the relevant information,

The idea of Java Programming (Fourth edition, page 5th, 5.4,p84) gives a good answer. Let me tell you the knowledge in the book according to my Own understanding:

This keyword can be understood in English as the demonstrative pronoun this, which is used to refer to something, for example: Look,this is a table. This refers to table.

In the design of the Java language , this also has a pointing relationship .

1. Background of the This keyword

Let me start by answering why the Java designer created the This keyword? I'll use a piece of code to explain why.

1 class person{2 public      Void Speak () {3           System.out.println ("one object to invoke Method"); 4     } 5      6 public     static void Main (string[] args) {7 person       p1=new person (), 8 person       p2=new person (), 9       p1.speak ();     P1 object to call Speak () method       p2.speak ();    P2 object to call the Speak () method

11}

(pro-Test) operation Result:

An object to invoke a method
An object to invoke a method

However, when there is only one speak () method, how does the compiler know if the Speak () method is P1 or is it called by P2? In order to be able to write code with simple, object-oriented syntax-that is, "Send messages to Objects"-the compiler does some behind the scenes work. It secretly passes the reference of the Manipulated object as the first argument to the Speak () method. So the method after the call has become this:

Person speak (P1);

Person speak (P2);

This is an internal form of expression . If we write this, the compiler will give you an error, but it will help you understand what the compiler is doing. Suppose you want to get a reference to the current object inside the method, because the reference is "secretly" passed in by the compiler, so no identifiers are available.

Thus, in order to solve the background problem of getting a reference to the current object within a method, the Java designer specifically designed the This keyword to obtain a reference to the current object within the method. The This keyword can only be used inside a method, representing a reference to the "object that called the method" . It can be said thatthe use of this is not different from the references of other new objects .

Note, however, that if you call another method of the same class inside a method, you can omit this and call it directly. Because the this reference in the current method is automatically applied to other methods in the same class. So, Xiao Zhang you can write code like this, the compiler will not error:

Class person{
public void Speak () {}
public void Eat () {
When you call another method of the same class inside a method, you can omit this and call it directly.
Speak (); The compiler is automatically translated into This.speak ().
}
public static void Main (string[] args) {
}
}

This is why the This keyword was created, Xiao Zhang Ah, in summary, the This keyword produces the background: in order to resolve the ' get a reference to the current object within the method ' issue . The This keyword is designed to get a reference to the current object inside the method.

The role of 2.this keywords

Three major functions:

1) distinguish between local variables and member variables with the same name ,this. Member variable calls the member variable in this class;

2) Call the methods in this class through this . Method () ;

3) Thisis a call between the constructor methods.

Gentlemen, perhaps you have only seen these three major functions, maybe foggy. In your letter, you say that you are learning about the three major features of object-oriented in Java ( encapsulation, inheritance, polymorphism), so I think you already understand the private encapsulation, extends inheritance, and know the set, get method, and Null parameters, the relevant concepts of the constructor method. The following procedure requires you to have these foundations above, if you do not have these foundations for the time being, do not worry, go first to look at these basics. After you understand these basics, you can look back and see the code below, and you'll have an epiphany!

If you already have these basics, I'll use a complete program to clarify the three functions of the This keyword.

Package Day_12;//person type public class Person {      private String name;      private int age;            The name in the public person (String name) {//string name is the function of the local         variable //This  1: distinguishes between local variables and member variables with the same name          this.name= Name The name in THIS.name is a member variable      } public person      (String name,int age) {          //role 3:this keyword calls          between constructor methods This (name);   Use this (name) to call the constructor of only one parameter name          this.age=age;      }            public void SetName (String name) {          this.name=name;      }      Public String GetName () {          return this.name;      }            public void Setage () {          this.age=age;      }      public int getage () {          return this.age;      }      }
Package Day_12;//worker class public class Worker extends person {public    Worker (String name,int age) {        super (name,age );  Super (Name,age) calls the parent class person's construction method with two arguments.    }        public void work () {        //action 2: This is used in themethod        System.out.println (this.getname () + "in the chopping tree! ");    }}

Using this.getname () there is the idea of encapsulation inside . Since I do not know who the object calling the GetName () method is, I use the vague concept of which object to invoke the work () method, which is the object that this refers to.

It is clear that the object of the worker class WK to invoke the work () method, which points to the WK object . So use This.getname () to get the properties in the WK object: Bald head strong.

Testing class: Test class

Package Day_12;public class Test {public   static void Main (string[] args) {       worker wk=new worker ("bald-headed Strong"); 
   wk.work ();      }}

(pro-Test) operation Result: bald-headed strong in chopping tree !

3. Methodology

These two questions prompted me to think about the background of this keyword and the three major effects of this. After telling you this, I think I have deepened my understanding of this. You later in the Java learning process encountered foggy problems, although give me a message, as long as I can understand, certainly straightforward to speak clearly, I hope I do the wrong place, everyone actively points out, we learn together, progress together. Learn a language, to think more, often summed up is a good state, more communication. Huang Bo the Lord is looking forward to share with you here!

Java keyword---The origin of this and its three major functions

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.