I have two questions concerning objects and the use of static in Java. I found I could best explain my questions if I asked them with the same background:
I have one main class in my program. First it initializes a lot of things and then it starts the run method which cycles through a while (true) loop.
I also have a lot of other classes such as let's say a circle which I create during the initialization in my main class and save in a local variable along the lines of myCircle = new Circle();
.
I have also made some classes of which all variables and methods are static.
I've noticed that I don't have to create an object of such a class during initialization because everything in it is static. Whenever I need something from one of those classes, I can just call it like StaticClass.someMethod()
or StaticClass.someVariable
.
This in contrast to the circle where I go myCircle.anotherMethod()
. Had I made that method static I could have used Circle.anotherMethod()
.
Now my question is: Why create a new object and save it if I can just make everything in that class static (assuming that I'll only ever need ONE such object)?
More importantly: One of my static classes has a ton of constants which are images that it reads from a file. Since I haven't made a constructor, I don't know when it is actually loading the images. There are several different occasions when I would call StaticClass.someImage
and I'm wondering if it is now loading the images from a file multiple times.
So my second question is: When does Java load all the variables of a static class which doesn't have a constructor? (in other words, when does it create that object?)