我可以在Java中更改变量的声明类型吗?

问题描述:

问:我可以更改Java中变量的声明类型吗?

Q: Can I change the declaration type for a variable in 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);
  }
}

但是尝试编译会产生以下消息:

But attempted compilation results in the message:

Error: variable s is already defined in method main(java.lang.String[])

奇怪的是,在交互式DrJava会话中重新声明变量的类型就可以了:

Oddly, re-declaring the type of a variable works just fine in an interactive DrJava session:

> String s = "Foo"
> int s = 1
> s
1

这是怎么回事?

我可以更改Java中变量的声明类型吗?

Can I change the declaration type for a variable in Java?

否,编译器知道 s 已存在于同一范围内,并且声明为 String 类型.

No, the compiler knows that s already exists within the same scope and is declared of type String.

我以前从未使用过DrJava,但作为交互式解释器,它也许可以消除第一个变量的作用域,并将其替换为新语句中声明的变量.

I've never used DrJava before but as an interactive interpreter, it may be able to de-scope the first variable and replace it with the one declared in the new statement.