我可以在Java中更改变量的声明类型吗? [英] Can I change declaration type for a variable in Java?

查看:47
本文介绍了我可以在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.

这篇关于我可以在Java中更改变量的声明类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆