|
|
|
|
Sometimes we need to initialize things in a way that cannot be handled using such simple initializers. Instance variables have constructor methods to accomplish this.Static InitializersClass variables need a different mechanism: static initializers For example:
A static initializer is like a class method, except:
There can be any number of static initializers -- they are executed in lexical order when the class is loaded. Static initializers are used, among other places, in classes that implement native methods (much later...). Initialization BlocksYou can also have an initialization block that does not have a static keyword prefix. It allows you to initialize instance fields, or to execute arbitrary code at instance initialization:
which produces: Executing initialization block Count now 1 Executing initialization block Count now 2 There are a number of potentially useful applications of this technique. |
|
This page was last modified on 02 October, 2007 |