Static Keyword in Java | Java For Beginner | Java Language | Java.



Static Keyword 

When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object. You can declare both methods and variables to be static.

The most common example of a static member is main( ). Main( ) is declared as static because it must be called before any objects 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:
  1. They can only call other static methods.
  2. They must only access static data.
  3. They cannot refer to this or super in any way.
Example:


// Demonstrate static variables, methods, and blocks.

class UseStatic
{
   static int a = 3;
   static int b;
   static void meth(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 args[])
   {
      meth(42);
   }
}







Output:


Static block initialized.
x = 42
a = 3
b = 12

Outside of the class in which they are defined, static methods and variables can used  independently of any object.For example, if you wish to call a static method from outside its class, you can do so using the following general form:

classname.method( )

See Example:-


class StaticDemo
{
   static int a = 42;
   static int b = 99;
   static void callme()
   {
      System.out.println("a = " + a);
   }
}
class StaticByName
{
   public static void main(String args[])
   {
      StaticDemo.callme();
      System.out.println("b = " + StaticDemo.b);
   }
}



Output:

a = 42
b = 99

Post a Comment

0 Comments