类范围变量可见性

时间:2014-01-14 08:54:02

标签: java

如果我有:

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必须在其之前声明 使用。

哪个是课程范围规则?它们与方法范围规则有何不同?

P.S。 我怀疑是因为共同范围决议规则: 当编译器找到count时,它应该尝试“回”到它 使用但后面有Class A...所以可能private int count正在“悬挂” Class A的开头?

2 个答案:

答案 0 :(得分:1)

想象一下你是一个编译器,你就到了这一行:

int a = c;

不会生气并问自己"什么是c"?顺序很重要 1

1 count没有问题,因为它是class member,它在全班都知道。您可以将班级成员放在班级的开头或最后。

答案 1 :(得分:0)

在类中声明了

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是方法中的局部变量。

相关问题