【发布时间】:2011-10-02 18:13:10
【问题描述】:
虽然我试图理解为什么需要“this”,但我对它的用途感到非常困惑。例如,我编写了以下代码:
public static void main (String args[])
{
SandboxClass1 temp = new SandboxClass1(1,2,3);
System.out.println(temp.getX());
System.out.println(temp.getY());
System.out.println(temp.getZ());
System.out.println("----------------------------");
SandboxClass1 temp2 = new SandboxClass1(4,5,6);
System.out.println(temp2.getX());
System.out.println(temp2.getY());
System.out.println(temp2.getZ());
}
public class SandboxClass1
{
private int x = 1;
private int y = 1;
private int z = 0;
public SandboxClass1(int x, int y, int zz)
{
this.x = x;
this.y = y;
z = zz;
}
public int getX()
{
return(this.x);
}
public int getY()
{
return(this.y);
}
public int getZ()
{
return(this.z);
}
}
为什么我需要编码“this.z = zz”
什么时候我也可以写“z = zz”?
【问题讨论】:
-
对于
z和zz,您不需要this。 -
在不强制的地方使用它,比如在你的 getter 中,只是编码风格的问题。
标签: java this operator-keyword