Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/400.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 类范围可变可见性_Java - Fatal编程技术网

Java 类范围可变可见性

Java 类范围可变可见性,java,Java,如果我有: class A { void foo() { int a = count; } void bar() { int a = c; // here ERROR int c = 10; } private int count = 10; } 这里的foocount如果是在使用后声明的,也可以毫无问题地使用。 在方法bar中,变量c必须在其 使用 哪些是类范围规则?它们与方法范围规则有何不同 附

如果我有:

class A
{
   void foo()
   {
      int a = count;      
   }

   void bar()
   {
      int a = c; // here ERROR
      int c = 10;
   }

   private int count = 10;

}
这里的
foo
count
如果是在使用后声明的,也可以毫无问题地使用。
在方法
bar
中,变量
c
必须在其 使用

哪些是类范围规则?它们与方法范围规则有何不同

附言。 我的怀疑是因为通用范围决议规则: 当编译器找到
count
时,它应该尝试找到它“返回”到它的 使用,但后面有
A类…
所以可能
私有整数计数

A类的开始

count
在类中声明,而
c
在方法中声明

编译时,类将在类中找到
count

class A
{
   void foo()
   {
      int a = count;      
   }
   private int count = 10;
}
等于在类中的任何位置放置
count
,因为它是类成员并且可以在类中的任何位置找到

而在你的情况下

class A
{
   void bar()
   {
      int a = c; // here ERROR
      int c = 10;
   }
}

c
在使用前未定义,因为
c
是方法中的局部变量。

假设您是一名编译器,然后进入以下行:

int a = c;
你会不会生气并问自己“什么是
c
”?顺序很重要


1
count
不成问题,因为这是一个,全班都知道的问题。您可以将类成员放在类的开头或结尾。

什么是
c
?您需要首先声明它,或者首先将其作为成员字段,为什么不在a之前声明c,然后看看发生了什么阅读Java中的所有作用域。