Redian新闻
>
help on this scope question
avatar
help on this scope question# Java - 爪哇娇娃
l*r
1
I have two pieces of code
1) has compilation error:
class TestScope {
public void test() {
int x = 2;
if ( true ) {
int x = 1;
System.out.println( "In if: " + x );
}
System.out.println( "Out If: " + x );
}
}
2) compiled and output is: In if: 1 Out If: 2
class TestScope {
int x = 2;
public void test() {
if ( true ) {
int x = 1;
System.out.println( "In if: " + x );
}
System.out.println( "Out If: " + x );
}
}
Can you tell me why Java support this differently?
Thanks!
avatar
n*k
2

~~~~~~~~~~~~
here is the compilation error
Because in the first example, there is no instance varible(or class variable)
nameed x exists other than the local varibale inside the method, so the scope
of the x is all over the method, and it can not be shadowed any other local
variable inside the method.
On the other hand, the second example has an instance variable x and also a
local block variable x, inside the if block, the local variable

【在 l***r 的大作中提到】
: I have two pieces of code
: 1) has compilation error:
: class TestScope {
: public void test() {
: int x = 2;
: if ( true ) {
: int x = 1;
: System.out.println( "In if: " + x );
: }
: System.out.println( "Out If: " + x );

avatar
h*b
3
Nod, agree, very clear explanation!

variable)
scope

【在 n*****k 的大作中提到】
:
: ~~~~~~~~~~~~
: here is the compilation error
: Because in the first example, there is no instance varible(or class variable)
: nameed x exists other than the local varibale inside the method, so the scope
: of the x is all over the method, and it can not be shadowed any other local
: variable inside the method.
: On the other hand, the second example has an instance variable x and also a
: local block variable x, inside the if block, the local variable

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。