Just getting my feet wet with Java so I apologize if this seems a bit naive. I’m trying to get a better understanding of the conventions for accessing instance / member variables in practice.
Can a non-static instance variable be manipulated from a
non-static context?
For instance, How could one modify the following class definition to allow the id and version variables to increment.
class Foo {
private int id;
private int version;
public String product;
public String model;
private Foo( ) {
// Can these variables be accessed from a non-static context?
id++;
version++;
}
...
In comparison with static fields …
class Foo {
private static int id;
private static int version;
public String product;
public String model;
private Foo( ) {
id++;
version++;
}
...
First Example …
1
1
Model One
First1
1
Model Two
Second
Second Example …
1
1
Model One
First2
2
Model Two
Second
You can access a
static-variablefrom anon-static context, becausestatic variablesare bound to a class. So, even if you access it within anon-static context, it is accessed just like instatic context.For e.g: –
Surprisingly the above code does not throw
NPE, as the static varible is accessed onclass nameregardless of how you are accessing it.So,
obj.staticVaris actually replaced withMyClass.staticVar.But the reverse is not true. You cannot access a
non-static variablefrom astatic context. Because, in a static context, you don’t have anyreferenceto an instance. And you can’t access instance variable without any reference to an instance of that class.Having said that, also note that, just because you can do something, doesn’t mean that it is a good idea. Modifying a
static variableinside aconstructoror in anynon-static contextis aterribleidea. Because, any change you make to those variables, will be reflected for all the instances of that class.Rather, you should use a
static-initialization blockto initialize thestaticvariables.Static initialization blockis executed atclass-loadingtime, to initialize all thestaticvariables.