我来自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,现在我明白了,谢谢! –