Thursday 15 March 2012

Static Concepts in java

Static Definition:
        In classes, a static method is one that is called without an instance of that class(object), while a non-static method is called by instances of the class(object).  

Static Program: 
package static_pack;
public class stat {
      static int i = 12;
      int j = 20;
      static
      {
            subclass sub = new subclass();
            System.out.println("The Static value is: " +i);
            //System.out.println("The Static value is: " +j);
           
            sub.display();
      }
      public static void main(String[] args)
      {
            System.out.println("Oops Main class after static block...");
            subclass.print();
      }
}
create a subclass class in the same package:

package static_pack;
public class subclass
{
      static void print()
      {
            System.out.println("In Subclass static method");
      }
      public void display()
      {
            System.out.println("Static yaar!!");
      }
}

Output:-
The Static value is: 12
Static yaar!!
Oops Main class after static block...
In Subclass static method

Explanation :
                 From the above program u can understand that Static block gets executed before the public static void main(String args[]). The static block gets executed and then the main block gets executed

Tags:
        Static program in java, Static program with Example, Static concept java, simple Static program,interview static,static program,use of static block,static block,Static function,Static Declaration

No comments:

Post a Comment