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

low*_*rul 11 java

问:我可以在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);
  }
}
Run Code Online (Sandbox Code Playgroud)

但尝试编译导致消息:

Error: variable s is already defined in method main(java.lang.String[])
Run Code Online (Sandbox Code Playgroud)

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

> String s = "Foo"
> int s = 1
> s
1
Run Code Online (Sandbox Code Playgroud)

这是怎么回事?

mpr*_*hat 6

范围内的变量名称是固定的,因此您不能拥有多个类型的相同变量.您可以使用两种不同类型但具有不同范围的相同名称.所以下面的例子如果你认为是好的,因为我们在两个不同的范围内改变类型.一个实例级别和第二次方法级别.

 public class Test {
    private String variable = "";

    private void init() {
        int variable = 10;
    }
}
Run Code Online (Sandbox Code Playgroud)


man*_*uti 6

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

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

我之前从未使用过DrJava,但作为一个交互式解释器,它可能能够解除第一个变量的范围并将其替换为新语句中声明的变量.


Vin*_*ent 5

不。

但是你可以尝试这样的事情

public class Tmp 
{
  public static void main(String[] args) 
  {
    {
      String s = "Foo";
      s = null;
    }
    int s = 3;
    System.out.println(s);
  }
}
Run Code Online (Sandbox Code Playgroud)

但你真的想要这个吗?如果变量的类型发生变化,读者可能会感到非常困惑。