|
|
Re: Calling non-static variable externally
|
Posted: Jan 24, 2007 10:15 PM
|
|
class ExampleClass {
public int nonStaticValue;
public static int staticValue;
}
class CallerClass {
public void someMethod() {
int i = ExampleClass.staticValue; //works
i = ExampleClass.nonStaticValue; //does not work
ExampleClass exampleInstance = new ExampleClass();
i = exampleInstance.nonStaticValue; //works
i = new ExampleClass().nonStaticValue; //works
}
}
A non-static variable [b]does not exist[/b] until you create an instance of the class. And also then you must call the variable using the instance, not the class name.
Only static variables and methods are visible using the class name.
quote:"I can't just make the variable static because it needs to be implemented with the paint method.
". Say what? "static" does not mean "final". I don't really understand why the variable can't be static.
The only thing you must pay attention to is that a static variable is independent from the instance. Means: If you create multiple instances of a classs, they will all have the same value for a static variable. If you change it for one instance, it's also changed for the other instances.
|
|