为什么Java没有块范围的变量声明? [英] Why does Java not have block-scoped variable declarations?

查看:86
本文介绍了为什么Java没有块范围的变量声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下方法不起作用,因为内部块声明了与外部块中的名称相同的变量。显然,变量属于声明它们的方法或类,而不属于声明它们的块,因此我无法编写一个简短的临时块来进行调试,这会将外部作用域中的变量推送到阴影一下:

The following method does not work because the inner block declares a variable of the same name as one in the outer block. Apparently variables belong to the method or class in which they are declared, not to the block in which they are declared, so I therefore can't write a short little temporary block for debugging that happens to push a variable in the outer scope off into shadow just for a moment:

void methodName() {
  int i = 7;
  for (int j = 0; j < 10; j++) {
    int i = j * 2;
  }
}

几乎我用过的每一种块范围的语言支持这一点,包括我在学校编写口译和编译器的琐碎小语言。 Perl可以这样做,就像Scheme一样,甚至是C.甚至PL / SQL也支持这个!

Almost every block-scoped language I've ever used supported this, including trivial little languages that I wrote interpreters and compilers for in school. Perl can do this, as can Scheme, and even C. Even PL/SQL supports this!

这个Java设计决策的基本原理是什么?

What's the rationale for this design decision for Java?

编辑:有人指出,Java确实有块范围。我问的概念是什么名字?我希望我能从那些语言设计课程中记住更多。 :)

as somebody pointed out, Java does have block-scoping. What's the name for the concept I'm asking about? I wish I could remember more from those language-design classes. :)

推荐答案

我认为理由是大多数时候,这不是故意的,而是编程或逻辑缺点。

I believe the rationale is that most of the time, that isn't intentional, it is a programming or logic flaw.

在一个像你一样微不足道的例子中,很明显,但是在一大块代码中,不小心重新声明变量可能并不明显。

in an example as trivial as yours, its obvious, but in a large block of code, accidentally redeclaring a variable may not be obvious.

ETA:它也可能与java中的异常处理有关。我认为这个问题的一部分是在一个问题中讨论的,该问题涉及为什么在try / section范围内没有在try部分中声明的变量。

ETA: it might also be related to exception handling in java. i thought part of this question was discussed in a question related to why variables declared in a try section were not available in the catch/finally scopes.

这篇关于为什么Java没有块范围的变量声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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