Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Plain "static" keyword inside class 1

Status
Not open for further replies.

Sen7inel

IS-IT--Management
Joined
Feb 14, 2001
Messages
90
Location
FI
Hi,

A class is defined as follow:

Code:
public class Blaa
{
  private static Whatever whatever;

  static {
    Blaa.whatever = new Whatever();
    ..
  }
}

What actually is the purpose of the static keyword there, and when does its content get executed?
 
The static keyword basically means that one instance of "whatever" is shared between multiple instances of a class.

It is useful for when multiple instances of a variable really aren't required for each instantiation such as global constants.

It is also useful, for example, when the class needs to keep track of the number of instances of itself. Like a video game that keeps track of how many enemies are on the screen. If a variable "enemyCount" is static, then it can be incremented and decremented each time an instance of enemy is introduced or eliminated respectively. Each instance of the class can change this one variable because they all share it.

Monitoring this variable, you can have your program introduce more "enemies" when enemyCount is less than 2 or something like that.
 
>> and when does its content get executed?

It will execute before any non-static lines of code execute

-pete
 
to add,
I actually use this a lot to call C methods using JNI(Java Native Interface). I need to have all these libraries loaded before any java objects can call these C methods.

All these static method is unique for the class. You can instantiate the java class to create java objects but they all use the same instance of these so called "JNI" interface libraries.

~za~
You can't bring back a dead thread!
 
static {
Blaa.whatever = new Whatever();
..
}

Above code is a static initializer block, which is used to initialize static variables.
You can have more than one static blocks.
Every static block gets executed before the execution of main program. Order of execution is the order in which they are written in source code.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top