Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to have multiple instances of static variables

Tags:

java

static

Static variables have only instance (that is they are part of the class). ex: Math.pi

Is there any way there could be multiple instances of static variables? I heard there is something related to Classloaders?

like image 907
Satish Avatar asked Jul 28 '10 03:07

Satish


People also ask

What is the difference between instance and static variables?

Static variables are created when the program starts and destroyed when the program stops. Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class.

Can a static variable be used outside of a class?

Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. There would only be one copy of each class variable per class, regardless of how many objects are created from it. Static variables are rarely used other than being declared as constants.

Can the same class have its own statics in multiple classes?

Yes, if the same class is loaded in different class loaders, then each copy of the class will have its own statics. However, the only code that can refer statically to those statics will be classes loaded by the same class loader. And of course, that code will only (statically) see the statics in one copy of the class.

What is a static variable in Java?

Static variables in Java. Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. There would only be one copy of each class variable per class, regardless of how many objects are created from it.


1 Answers

If you find that you need multiple instances of a static variable, this is a strong indication that you should not be using static variables in the first place.

Yes, if the same class is loaded in different class loaders, then each copy of the class will have its own statics. However, the only code that can refer statically to those statics will be classes loaded by the same class loader. And of course, that code will only (statically) see the statics in one copy of the class. So you probably haven't achieved a lot.

Rather than messing around with classloaders, you should be refactoring your code to turn the static variables into instance variables.

like image 197
Stephen C Avatar answered Nov 15 '22 07:11

Stephen C