我试图完全理解“这个”是如何工作的。在我之前的帖子中,我理解了为什么我们使用“this”关键字。
我对静态的理解是该类具有该成员的一个副本。“this”用于表示当前对象。对于所有对象,静态成员变量都是相同的,那么为什么“this”对静态成员变量起作用?
代码:
public class OuterInnerClassExample
{
public static void main(String[] args)
{
OuterClass outClassObj = new OuterClass(10);
outClassObj.setInt(11);
outClassObj.setInt(12);
System.out.println("Total Count: " + outClassObj.getCount() );
}
}
class OuterClass
{
private int test;
private static int count; // total sum of how many new objects are created & the times all of them have been changed
public OuterClass(int test)
{
this.test = test;
// count += 1; // preferred as count is static
this.count += 1; // why does this work
}
public int getInt()
{
return this.test;
}
public int getCount()
{
return this.count;
}
public void setInt(int test)
{
this.test = test;
// count += 1; // preferred as count is static
this.count += 1; // why does this work
}
class SomeClass
{
private OuterClass outClassObj;
public SomeClass(int var)
{
outClassObj = new OuterClass(var);
}
public int getVar()
{
return this.outClassObj.getInt();
}
public int getCount()
{
return this.outClassObj.getCount();
}
public void setVar(int var)
{
// OuterClass.this.test = var; // can do this
outClassObj.setInt(var); // preferred
// OuterClass.count += var; // should do this
OuterClass.this.count += var; // why does this work
}
}
}
另外,在 setVar 方法中,我们可以使用 ClassName.this 来操作对象的值,但我认为使用 setter 更好,因为它更清晰。我错过了在这里使用“这个”有什么好处吗?
请发布代码以显示您要解释的示例。