4.11 Class Initialization

There is a special static method called <clinit> that is used to initialize the class as a whole. It's often used to initialize static fields. The <clinit> method takes no arguments and returns nothing. It is called by the JVM when the class is loaded; there's no need for you to call it. For example,

 ; This class represents all the possible kinds of ice cream .class IceCream ; These are the possible kinds of ice cream: .field final public static vanilla LIceCream; .field final public static chocolate LIceCream; .field final public static strawberry LIceCream; ; A private constructor: only I can create IceCream objects .method private <init>()V aload_0 invokespecial java/lang/Object/<init> ()V    ; Call the superclass                                              ; constructor return .end method ; The class constructor .method static <clinit> ()V .limit stack 2 new IceCream                            ; Create an IceCream dup invokespecial IceCream/<init> ()V putstatic IceCream/vanilla LIceCream;   ; Store it in vanilla new IceCream                            ; Create another IceCream dup invokespecial IceCream/<init> ()V putstatic IceCream/chocolate LIceCream;   ; Store it in chocolate new IceCream                              ; Yet another IceCream dup invokespecial IceCream/<init> ()V putstatic IceCream/strawberry LIceCream;  ; Store it in Strawberry return .end method 

The fields vanilla, chocolate, and strawberry hold the instances of the class IceCream. The fields are set when the class is loaded by the <clinit> method.

Because the constructor is private, nobody can create new flavors without modifying the IceCream class. This is sometimes better than using int values to represent flavors. If you have an IceCream object, you can be sure that it is of one of the three recognized flavors, no others.



Programming for the Java Virtual Machine
Programming for the Javaв„ў Virtual Machine
ISBN: 0201309726
EAN: 2147483647
Year: 1998
Pages: 158
Authors: Joshua Engel

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net