What is 1.this?
This is a reference type that has a this,this memory address pointing to itself on every Java object in the heap.
Where can 2.this be used?
First: This can be used in member methods.
Second: This can be used in the construction method.
Syntax: this (argument);
A constructor method is used to invoke another constructor.
Purpose: Code reuse.
This (argument); must appear in the first row of the construction method
Third: This cannot be used in static methods. The execution of a static method does not require the existence of a Java object, directly using the "class name." Way to access, this represents the current object, all of which are not used in static methods.
class mydate{//fieldint year;int month;int day;// constructor//requirements: When creating a Date object, the default date is: 1970-1-1mydate () {this (1970,1,1);/*this.year = 1970;this.month = 1;this.day = 1;*/}mydate (int _year,int _month,int _day) {year = _year;month = _month;day = _day;}
/*this can be used in member methods. This is the current object. */public class Thistest02{public static void Main (string[] args) {//Create object Employee E = new Employee (7369, "SMITH" );//Work e.work ();//Create object Employee e1 = new Employee (7370, "FORD");//Work e1.work (); E.m1 ();}} Class employee{//Employee number int empno;//Employee name String Ename;//constructoremployee () {}employee (int _empno,string _ename) {empno = _empno;ename = _ename;} Provides a way for an employee to work.//this in the member method, who calls this member method, this represents who. This refers to the current object. public void works () {System.out.println (This.ename + "at Work");//system.out.println (ename + "at Work");//this. can omit}// Member method public void M1 () {this.m2 (); M2 ();} Member method public void M2 () {System.out.println ("testing");}}
Note: This cannot be used in static methods.
/*this cannot be used in static methods. The execution of a static method does not require the existence of a Java object at all. Use the class name directly. The way to access it. This represents the current object. So there is no This*/public class thistest04{string at all in the static method str;//entry public static void main (string[] args) {person.m1 ();/ STR is a member variable that must be referenced by. Access to//SYSTEM.OUT.PRINTLN (str); ThisTest04 tt = new ThisTest04 (); System.out.println (TT.STR); Null}}class person{//fieldstring Name;//constructorperson () {}person (String name) {this.name = name;} static method public static void M1 () {//system.out.println (this.name);//If you want to access name only: person p1 = new Person ("Andy Lau"); System.out.println (P1.name);}}
This article is from the "Gaogaozi" blog, make sure to keep this source http://hangtiangazi.blog.51cto.com/8584103/1661111
The This keyword in Java