我來自Python的Java,並認爲this
基本上像Python的self
...但這個小代碼混淆了我。在功能上,此代碼:推理和範圍(我認爲與範圍有關)
public class Test {
private String name;
public Test(String givenName)
{
this.name = givenName;
}
public String nameGet()
{
return this.name;
}
public static void main(String[] args)
{
Test example = new Test("Hello Guys");
System.out.println(example.nameGet());
}
}
做同樣的事情,因爲這代碼:
public class Test {
private String name;
public Test(String givenName)
{
name = givenName;
}
public String nameGet()
{
return name;
}
public static void main(String[] args)
{
Test example = new Test("Hello Guys");
System.out.println(example.nameGet());
}
}
由於這一點,原諒雙關語,似乎是這種情況,那麼,什麼是在課堂上工作時提到這一點?
所以第一個構造函數正在做什麼呢?由於givenName不是局部變量,發生了什麼? –
給定name是一個局部變量......它是構造函數的一個參數,它的值爲「Hello Guys」代碼在你的例子中給出 – TofuBeer
Doh!OKay,現在我明白了,謝謝! –