Static variable and method


when you will want to define a class member that will be used independently of any object of that  class. normally a class member must be accessed only in conjunction with an object of its class. normally a class member must be accessed only in conjunction with an object of its class. it is possible to create a member that can be used by itself, without reference to a specific instance. to create such a member ,precede its declaration with the keyword static. when a member is declare, it can be accessed before any objects of its class are created, and without reference to any object.

  •   you can declare both method and variable to be static.
  •   main() is declared as static because it must be called before any object exist.
Instance variables declared as static are, essentially, global variables. when objects of its class are declared, no copy of a static variable is made. Instead ,all instances of the class share the  same static variable.

methods declared as static have several restrictions:----------
  •   they can only call other static methods.
  •   they must only access static data.
  •   they cannot refer to this or super in any way.(the keyword super relates to inheritance)
 

class T12
{
static int a=66;
static int b;
static void test(int x)
{
System.out.println("X="+x);
System.out.println("a="+a);
System.out.println("b="+b);
}

static
{
System.out.println("static block initialized");
b=a*4;
}
public static void main(String as[])
{
test(55);

}
      }

/*
E:\>java T12
static block initialized
X=55
a=66
b=264
*/
when Use Static class is loaded, all of the static statements are run. first set a=66 then the static block executes, and finally ,b is initialized to a*4 or 264. then main is called, which calls test(),passing 77 to x. the three println() statements refer to the two static variable a and b. if you wish to call a static method from outside its class by
                                             classname.method()
here classname is the name of the class in which the static method is declared.
class Stat
{
static int a=33;
static int b=44;
static void callme()
{
System.out.println("a="+a);
}
}


class S1
{
public static void main(String as[])
{
Stat.callme();
System.out.println("b="+Stat.b);
}
}



OUTPUT:

a=33
b=44




0 comments :

Post a Comment