調用函數時,this
和.this
之間有什麼區別?而且,當使用this
或this.
時會發生什麼?這和.this之間的區別?
實施例:
class reference
{
public void object()
{
reference obj = new reference();
this.obj();
}
}
調用函數時,this
和.this
之間有什麼區別?而且,當使用this
或this.
時會發生什麼?這和.this之間的區別?
實施例:
class reference
{
public void object()
{
reference obj = new reference();
this.obj();
}
}
當您有需要參照其封閉類的instance.It僅在情況下,使用有一個內部類的非靜態嵌套類Class.this
語法是有用的,並且需要引用封閉類
在實例方法或構造函數中,this
是對當前對象的引用 - 該對象的方法或構造函數被調用。您可以使用this
從實例方法或構造函數中引用當前對象的任何成員。
一個很好的例子
public class TestForThis {
String name;
public void setName(String name){
this.name = name;
}
public String getName() {
return name;
}
class TestForDotThis {
String name ="in";
String getName() {
return TestForThis.this.name;
}
}
public static void main(String[] args) {
TestForThis t = new TestForThis();
t.setName("out");
System.out.println(t.getName());
TestForThis.TestForDotThis t1 = t.new TestForDotThis();
System.out.println(t1.getName());
}
}
輸出將是
out
out
只是一個小提示:「非靜態嵌套」(或簡稱「內部」)並不意味着「有一個封閉實例」。 – 2014-09-13 13:31:20
哦。所以.this語法僅在類必須引用另一個類的實例時使用,而此語法用於當前調用方法/構造函數的對象,對嗎? – 2014-09-13 13:38:48
好的,我開始明白這一點。但是,您可以添加一些意見以便更好地理解?我將衷心感謝您的幫助! – 2014-09-13 13:46:02
'.this'不是Java中的有效的表達式。你已經把它從背景中剝離出來了。 – 2014-09-13 13:22:37
很高興看到你指的是一個小例子。我只能假設你正在使用它們的上下文。 – hexafraction 2014-09-13 13:22:45
你很可能意味着'this'和'SomeClass.this'之間的區別。 – 2014-09-13 13:24:41