數據加載中……
          特殊變量this

          This變量表示成員對象本身。

          public class point

          {

          ????int x,y;

          ????point(int a,int b)

          ????{

          ????????x=a;

          ????????y=b;

          ????}

          ????point()

          ????{????????

          ????}

          ????void output()

          ????{

          ????System.out.println(x);

          ????System.out.println(y);

          ????}

          ????void output(int x,int y)

          ????{

          ????????this.x=x;

          ????????this.y=y;

          ????}

          ????public static void main(String[] args)

          ????{

          ????????point pt;

          ????????/*pt=new point();

          ????????{

          ????????????

          ????????????pt.output();????????????

          ????????}*/

          ????????pt=new point(3,3);

          ????????{

          ????????????pt.output(5,5);

          ????????????pt.output();

          ????????}

          ????}

          }

          當類中有2個同名變量,一個屬于類(類的成員變量),而另一個屬于某個特定的方法(方法中的局部變量),使用this區分成員變量和局部變量。

          使用this簡化構造函數的調用。

          public class point

          {

          ????int x,y;

          ????point(int a,int b)

          ????{

          ????????x=a;

          ????????y=b;

          ????}

          ????point()

          ????{????

          ????????this(1,1);

          ????}

          ????void output()

          ????{

          ????System.out.println(x);

          ????System.out.println(y);

          ????}

          ????void output(int x,int y)

          ????{

          ????????this.x=x;

          ????????this.y=y;

          ????}

          ????public static void main(String[] args)

          ????{

          ????????point pt;

          ????????pt=new point();

          ????????pt.output();

          ????}

          }

          我們使用一個不帶參數的構造方法來調用帶參數的構造方法,在不帶參數的構造方法中使用this(1,1);this本身表示pt對象,他調用帶參數的成員方法,來給x和y賦值。大大簡化了調用方法。

          在一個類中所有的實例(對象)調用的成員方法在內存中只有一份拷貝,盡管在內存中可能有多個對象,而數據成員(實例變量,成員變量)在類的每個對象所在的內存中都存在著一份拷貝。This變量允許相同的實例方法為不同的對象工作。每當調用一個實例方法時,this變量將被設置成引用該實例方法的特定的類對象。方法的代碼接著會與this所代表的對象的特定數據建立關聯。

          posted on 2008-03-05 13:57 rick 閱讀(181) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發表評論。


          網站導航:
          博客園   IT新聞   Chat2DB   C++博客   博問  
           
          主站蜘蛛池模板: 易门县| 六安市| 温州市| 英山县| 内江市| 宁陵县| 嘉义市| 阳谷县| 涪陵区| 乌什县| 襄垣县| 阿尔山市| 东阿县| 商城县| 林州市| 公安县| 金乡县| 兴山县| 沅江市| 洛宁县| 姜堰市| 平武县| 静乐县| 望奎县| 镇沅| 安国市| 伊宁市| 康马县| 余姚市| 盈江县| 进贤县| 宜州市| 仙居县| 梓潼县| 香港 | 荆门市| 务川| 抚松县| 小金县| 仁怀市| 岑巩县|