up previous next contents
Next: Garbage collection and finalize Up: Classes and objects Previous: Static members   Contents

Initialization Blocks

  • A class can have initialization blocks to set up fields or other necessary states.
  • Typically these blocks are static.
  • Most useful when simple initialization clauses on a field declaration need a little help.
        class Primes {
           protected static int[] knownPrimes = new int[4];
           static
           {
              knownPrimes[0] = 2;
              for (int i=1; i<knownPrimes.length; i++)
              {
                 knownPrimes[i] = nextPrime();
              }
           }
        }
    
  • You can also have non-static initialization blocks.


up previous next contents
Next: Garbage collection and finalize Up: Classes and objects Previous: Static members   Contents