1
class A {
    public int someVar;
    someVar = 123;      /* cannot find symbol */
}

为什么语言看不到我刚刚声明的变量?这是 Java 独有的,还是在所有有类 OOP 语言中都是如此?

4

5 回答 5

9

在 Java 中,您可以在类内部和方法外部声明实例变量,但诸如someVar = 123;必须在方法(或构造函数、静态初始化程序或实例初始化程序)内的语句。

于 2013-09-03T20:06:30.210 回答
6

类定义中不能有任意语句。您可以立即在声明中分配变量:

public int someVar = 123;

或者,在构造函数或其他实例范围内分配它:

public class A {
  public int someVar;

  public A() {
    someVar = 123;
  }
}
//Or...
public class B {
  public int someVar;
  { someVar = 123; }
}

请注意,第二种技术使用实例初始化程序,它并不总是最直接清晰的代码。

于 2013-09-03T20:07:07.043 回答
2

您不能someVar = 123;直接在类中声明语句。
它应该是instance块或in methodconstructor

 class A {
    public int someVar = 123;
}

或者

class A {

    public int someVar ;
    {
          somevar = 123;
    }
}

或者

class A {

        public int someVar ;
        A(){
              somevar = 123;
        }
    }

或者

class A {

        public int someVar ;
        public void method(){
              somevar = 123;
        }
    }
于 2013-09-03T20:08:19.433 回答
1

但是,奇怪的是,你可以编码

public class AFunnyClass {
    public int someVar;
    {
        someVar = 123;
    }
    public static int anotherVar;
    static {
        anotherVar = 456;
    }
    public int yetAnotherVar = 789;
    public static int adNauseum = 101112;
}
于 2013-09-03T20:12:10.267 回答
0

Maybe you want to use someVar as a static variable. Then you should declare it also static. Using it like:

class A {
    static public int someVar = 123; 
}

That means someVar isn't just a member of an instance of this Class, it becomes a member of the class it self. That also means someVar will be instantiated just once and can be used by all instances of this Class

于 2013-09-03T20:13:57.087 回答