Reputation: 1696
I want to know if it is possible to use a static variable inside a non static methode ?
also
can I use a non static variable inside a static methode ?
Thanks
Upvotes: 0
Views: 279
Reputation: 42062
A static variable can be accessed from anywhere you like. A non static variable can only be accessed from a non static method or from a specific object (instance of a class).
The reason for this can get quite complicated, but in brief:
Anything that is non static in your class is duplicated whenever an object is instantiated from that class. Anything static is common to all instances of the class (and not duplicated for new objects), meaning it is unaffected by changes in the state of individual objects.
Now obviously until an instance of the class has been created, anything non static cant exist - there's no object for them to belong to. Since static members dont require an instance of a class to exist, it wouldnt be safe for them to access members that do require an instance of an object (non static).
Upvotes: 4
Reputation: 29710
Both are possible, but to access an instance (non-static) variable you need an instance.
This can be given implicitly in a non-static context like in an instance method, and must be provided explicitly in a static context.
class StaticOrNot {
static int staticVar = 1;
int instVar = 2;
static void staticMethod() {
staticVar += 1;
StaticOrNot someInstance = new StaticOrNot();
someInstance.instVar += 2;
}
void nonStatic() {
staticVar += 1;
instVar += 2; // using this as instance
}
}
Upvotes: 3
Reputation: 38561
Think about what it means to use a non-static variable in a static context. A static method is not executing on any instance - therefore, what would it mean to operate on a member field defined on the class? What instance does that field belong to? None!
The opposite scenario, namely, using a static variable in a non-static context makes perfect sense. You're on an instance, and you want to read some static reference that is defined for all instances of a given class.
Upvotes: 1
Reputation: 346476
I want to know if it is possible to use a static variable inside a non static methode ?
Yes.
can I use a non static variable inside a static methode ?
Only if you have an instance of the class available inside that static method.
Upvotes: 0
Reputation: 55172
I want to know if it is possible to use a static variable inside a non static methode ?
Yes.
can I use a non static variable inside a static methode ?
No.
Upvotes: 1