与 C 不同,在 Java 中,在较小的范围内声明同名变量是非法的,因为它可能是编程错误的来源,对吧?
public static void main(String[] args)
{
int n;
{
String n; //illegal in Java as they have same name.
}
}
但是为什么这个规则在创建构造函数时不适用呢?(这只是一些设计缺陷吗?)
class FirstTime
{
private int instanceField;
public FirstTime(int arg)
{
int instanceField=arg; //Why is this legal in Java? Isn't this the same concept like the above code
}
}
编辑:这个链接为什么你可以在java中为方法之外的变量使用重复的变量名?类似,但在重复的问题中,变量的范围“完全不同”,就像一个在main方法中,一个在方法外。但在我的例子中,两者都在课堂FirstName上,不是吗?