国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

java中this的用法示例(關鍵字this)

2019-11-26 15:34:35
字體:
來源:轉載
供稿:網友

this是指向本身的隱含的指針,簡單的說,哪個對象調用this所在的方法,那么this就是哪個對象。

示例代碼: TestThis_1.java

復制代碼 代碼如下:

/* 問題:什么是this
 * 輸出結果:
 * A@4e44ac6a
 */

public class TestThis_1 {
    public static void main(String[] args) {
        A aa = new A();
        System.out.println(aa.f()); //aa.f(), 返回aa這個對象的引用(指針)
    }  
}

class A {
    public A f() {
        return this;  //返回調用f()方法的對象的A類對象的引用
    }  
}

this的常見用法

1. 區分同名變量

示例代碼: TestThis_2.java

復制代碼 代碼如下:

/* this的常見用法1:區分同名變量
 * 輸出結果:
 * this. i = 1
 * i = 33
 */
public class TestThis_2 {
    public static void main(String[] args) {
        A aa = new A(33);
    }  
}

class A {
    public int i = 1;                                           //這個i是成員變量

    /*注意:一般不這么寫,構造函數主要是為了初始化,這么寫主要是為了便于理解*/
    public A(int i) {                                           //這個i是局部變量
        System.out.printf("this. i = %d/n", this.i);            //this.i指的是對象本身的成員變量i
        System.out.printf("i = %d/n", i);                       //這里的i是局部變量i
    }  
}

2. 構造方法間的相互調用

示例代碼: TestThis_3.java

復制代碼 代碼如下:

/* this的常見用法2: 構造方法中互相調用*/
public class TestThis_3 {
    public static void main(String[] args) {

    }  
}

class A {
    int i, j, k;
    public A(int i) {
        this.i = i;
    }  

    public A(int i, int j) {
        /* i = 3;  error   如果不注釋掉就會報錯:用this(...)調用構造方法的時候,只能把它放在第一句
         * TestThis_3.java:20: error: call to this must be first statement in constructor
         *      this(i);
         *                  ^
         *                  1 error
         */
        this(i);   
        this.j = j;
    }  

    public A(int i, int j, int k) {
        this(i, j);
        this.k = k;
    }  
}

注意事項

被static修飾的方法沒有this指針。因為被static修飾的方法是公共的,不能說屬于哪個具體的對象的。

示例代碼: TestThis_4.java

復制代碼 代碼如下:

/*static方法內部沒有this指針*/
public class TestThis_4 {
    public static void main(String[] args) {

    }  
}

class A {
    static A f() {
        return this;
        /* 出錯信息:TestThis_4.java:10: error: non-static variable this cannot be referenced from a static context
         *          return this;
         *                     ^
         *                     1 error
         */
    }  
}

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 上饶县| 平武县| 平泉县| 嵊泗县| 内黄县| 黑山县| 屏边| 政和县| 防城港市| 深水埗区| 邯郸县| 巨鹿县| 东安县| 张家界市| 聂拉木县| 永平县| 安阳市| 会东县| 新安县| 沙河市| 南汇区| 临高县| 铜山县| 邻水| 大宁县| 叶城县| 前郭尔| 乌兰察布市| 德昌县| 思南县| 孟州市| 荣昌县| 乐业县| 琼海市| 库伦旗| 化州市| 浦县| 年辖:市辖区| 牡丹江市| 南溪县| 平顶山市|