问:我可以更改 Java 中变量的声明类型吗?
例如,
public class Tmp{
public static void main(String[] args) {
String s = "Foo";
s = null; //same Error results whether this line included or not
int s = 3;
System.out.println(s);
}
}
但尝试编译导致消息:
Error: variable s is already defined in method main(java.lang.String[])
奇怪的是,重新声明变量的类型在交互式 DrJava session 中工作得很好:
> String s = "Foo"
> int s = 1
> s
1
这是怎么回事?
最佳答案
Can I change the declaration type for a variable in Java?
不,编译器知道 s
已经存在于相同的范围内并且被声明为 String
类型。
我以前从未使用过 DrJava,但作为交互式解释器,它可能能够取消第一个变量的作用域并将其替换为在新语句中声明的变量。
关于java - 我可以更改 Java 中变量的声明类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27092245/