class A {
public int someVar;
someVar = 123; /* cannot find symbol */
}
Why cant the language see the variable I just declared? And is this unique to Java or this is true in all classful OOP languages?
class A {
public int someVar;
someVar = 123; /* cannot find symbol */
}
Why cant the language see the variable I just declared? And is this unique to Java or this is true in all classful OOP languages?
In Java, you can declare instance variables inside a class but outside a method, but statements such as someVar = 123;
must be within a method (or a constructor, a static initializer, or an instance initializer).
You can't have arbitrary statements in a class definition. You can either immediately assign the variable in the declaration:
public int someVar = 123;
Or, assign it in a constructor or other instance scope:
public class A {
public int someVar;
public A() {
someVar = 123;
}
}
//Or...
public class B {
public int someVar;
{ someVar = 123; }
}
Note that the second technique uses an instance initializer, which is not always the most immediately clear piece of code.
You can not declare someVar = 123;
statement directly in class.
It should be instance
block or in method
or in constructor
class A {
public int someVar = 123;
}
or
class A {
public int someVar ;
{
somevar = 123;
}
}
or
class A {
public int someVar ;
A(){
somevar = 123;
}
}
or
class A {
public int someVar ;
public void method(){
somevar = 123;
}
}
But, oddly, you can code
public class AFunnyClass {
public int someVar;
{
someVar = 123;
}
public static int anotherVar;
static {
anotherVar = 456;
}
public int yetAnotherVar = 789;
public static int adNauseum = 101112;
}
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