Wednesday, 18 November 2009

Use of static

static can be used in multiple places


static block

static methods

static variables


static block

  • static blocks are run first when a class executes.
  • If a class contains main method , they will be executed before call to main method
  • There can be any number in a class , run in the order of appearance in source file
  • Can access only static methods and static variables
General form

static
{
// code to execute
}

example

class test
{

public static void main ( String args [ ] )
{
System.out.println ("In main") ;
} // main function ends

// static block
static
{
System.out.println ("In static") ;
}
} // class ends

Output : In static
              In main

static methods

There may be some processing which is not linked to any one object ,
but is general or applies to all objects in a common manner

  • Their declaration is preceded by keyword static
  • They can access only static methods and static variables
  • They can be accessed by class name also
                              classname.methodName 

example

static double getPi ()
{
double value = 3.1415 ;
return value ;
}

Regardless of object , value of PI remains same so we declare a function returning
value of PI as static

static variables

  • There may be property of a class which is not linked to any one object ,
          it is a class property . Such properties are declared static.

  • Their declaration is preceded by keyword static
  • They can be accessed by class name also
                                 classname.propertyName ;

  • Some practical examples are serial number , colour codes
  • There is only one copy of static variables and all objects share it
exmple

class test
{
static int serial = 0 ;

public static void main ( String args [ ] )
{

test t1 = new test () ;
test t2 = new test () ;
test t3 = new test () ;

System.out.println (t1.increment()) ; // 1
System.out.println (t2.increment()) ; // 2
System.out.println (t3.increment()) ; // 3

} // main function ends

static int increment ()
{
serial ++ ;
return serial ;
}    // function ends

} // class ends

Output:  1
             2
             3

As there is single copy of serial , we get incremental output

Difference from non static

Check what's the output when serial is instance variable and increment is non
static method