我可以在 Java 中更改变量的声明类型吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27092245/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I change declaration type for a variable in Java?
提问by lowndrul
Q:Can I change the declaration type for a variable in Java?
问:我可以在 Java 中更改变量的声明类型吗?
For e.g.,
例如,
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[])
Oddly, re-declaring the type of a variable works just fine in an interactive DrJava session:
奇怪的是,在交互式 DrJava 会话中重新声明变量的类型工作正常:
> String s = "Foo"
> int s = 1
> s
1
What's going on?
这是怎么回事?
采纳答案by M Anouti
Can I change the declaration type for a variable in Java?
我可以在 Java 中更改变量的声明类型吗?
No, the compiler knows that s
already exists within the same scope and is declared of type String
.
不,编译器知道s
在同一范围内已经存在并且声明为类型String
。
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.
我以前从未使用过 DrJava,但作为交互式解释器,它可能能够取消第一个变量的范围并将其替换为在新语句中声明的变量。
回答by mprabhat
Variable names inside a scope is fixed, so you cannot have same variable with multiple types. You can have same name with two different type but in a different scope. So below example if you consider is fine since we are changing type in two different scope. One instance level and second time method level.
作用域内的变量名是固定的,因此不能有多个类型的同一个变量。您可以具有两种不同类型但在不同范围内的相同名称。所以下面的例子如果你认为很好,因为我们在两个不同的范围内改变类型。一个实例级别和第二个时间方法级别。
public class Test {
private String variable = "";
private void init() {
int variable = 10;
}
}
回答by Vincent
No.
不。
But you can try something like this
但是你可以尝试这样的事情
public class Tmp
{
public static void main(String[] args)
{
{
String s = "Foo";
s = null;
}
int s = 3;
System.out.println(s);
}
}
But do you really want this? It can be really confusing for the readers, if the type of a variable changes.
但你真的想要这个吗?如果变量的类型发生变化,读者可能会感到非常困惑。
回答by Costis Aivalis
You can not change the declaration of a variable within the same scope.
您不能在同一范围内更改变量的声明。
Since everything in Java is an Object, you can as well declare s as an Object and let it become anything you like...
由于 Java 中的一切都是对象,因此您也可以将 s 声明为对象,并让它成为您喜欢的任何东西...
If drjava allows you to redeclare the variable within the same scope then its behavior is odd. Report the error.
如果 drjava 允许您在同一范围内重新声明变量,则其行为很奇怪。报告错误。
This code should work:
此代码应该工作:
Object s;
s="Foo";
System.out.println(s);
s=3;
System.out.println(s);