this的用法

关于this的用法

this关键字只能在方法内部使用,表示对“调用方法的那个对象”的引用。

this关键字主要有三个应用:
  1.this调用本类中的属性,也就是类中的成员变量;
 2.this调用本类中的其他方法(成员方法);
 3.this调用本类中的其他构造方法,调用时要放在构造方法的首行。
4.代表自身对象

1. this调用本类中的其他方法(成员方法)

如果在一个方法中调用同一个类中另外的方法可以不使用this,如:

 1 public class TestClass {
 2     public void test1(){
 3         System.out.println(123);
 4     }
 5     public void test2(){
 6         test1();
 7         /*
 8          * this.test1();这种写法也可以
 9          * 不过一般我们不这样写
10          */
11     }
12 }

 2.代表自身对象(当前对象)

 1 public class TestClass {
 2     public void test(){
 3         System.out.println(this);
 4     }
 5     public static void main(String[] args) {
 6         TestClass t=new TestClass();
 7         t.test();
 8     }
 9     /*
10      * 输出结果test.TestClass@15db9742
11      */
12 }

3.this调用本类中的其他构造方法,调用时要放在构造方法的首行。

 1 package test;
 2 
 3 public class demo {
 4     int petalCount=0;
 5     String s="abc";
 6     
 7     demo(int petal){
 8         this.petalCount=petal;
 9         /*
10          * petalCount=petal表达式相当于this.petalCount=petal,
11          * 因为参数和变量名不重叠,所以this可以省略,
12          * 如果参数也是petalCount,则只能使用this.petalCount=petal表达式;
13          */
14         System.out.println("参数为int类型的构造器: "+petal);
15     }
16     demo(String ss){
17         System.out.println("参数为String类型的构造器: "+ss);
18         //s=ss表达式相当于this.s=ss;
19         this.s=ss;
20     }
21     demo(String s,int petal){
22         /*
23          * 只能用this调用一个构造器
24          * 且this必须位于第一行
25          */
26         this(petal);
27         //this(s);
28         this.s=s;
29         System.out.println("String和int类型参数的构造器");
30     }
31     demo(){
32         this("hi",47);
33         System.out.println("无参构造器");
34     } 
35     void printPetalCount(){
36         //不在非构造函数内,不能使用
37         //this(11);
38         System.out.println("printPetalCount方法输出结果:patalCount= "+ petalCount +"    s= "+s );
39     }
40     public static void main(String[] args) {
41     demo d=new demo();
42     d.printPetalCount();
43     }
44 }
45 /*
46  * 输出结果
47  * 参数为int类型的构造器: 47
48  * String和int类型参数的构造器
49  * 无参构造器
50  * printPetalCount方法输出结果:patalCount= 47    s= hi
51  */
原文地址:https://www.cnblogs.com/whx20100101/p/7522273.html