特殊變量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所代表的對象的特定數據建立關聯。