數據加載中……
          特殊變量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 閱讀(178) 評論(0)  編輯  收藏


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


          網站導航:
           
          主站蜘蛛池模板: 景泰县| 铅山县| 蒙城县| 监利县| 连山| 滨州市| 遂溪县| 咸宁市| 榆社县| 奉化市| 东港市| 高雄县| 苍溪县| 滨海县| 左贡县| 双桥区| 南宫市| 苍梧县| 门头沟区| 大竹县| 交城县| 武平县| 格尔木市| 岐山县| 宜川县| 平湖市| 清流县| 达州市| 攀枝花市| 本溪市| 泰来县| 大悟县| 丰城市| 金门县| 永康市| 宣化县| 仲巴县| 绵竹市| 静安区| 澳门| 绥中县|