Pages

Saturday 2 March 2013

Static In Java

Static in java covers the followings:-

  1. static variables
  2. static methods
  3. static blocks 

 Static Variables
  • Static variables belong to the the class and not to the object or instance.
  •  A single copy of the static variable is shared among all the instances of the class
  • Static variables are initialized only once .this initialization happens at the start of the execution. These variables will be initialized first before initialization of any any instance variables.
  • a static variable can be accessed directly by the class name  and does not need any object creation.
  • Syntax :- ClassName.Variablename
 Example:-

 public class Bicycle {
       
        private int cadence;
        private int gear;
        private int speed;
       
        // add an instance variable for the object ID
        private int id;
   
        // add a class variable for the
        // number of Bicycle objects instantiated
        private static int numberOfBicycles = 0;
            ...
}


 The class variable can be called by the class name itself:

Bicycle.numberOfBicycles

From this we can know that they are class variables.

However we can also refer to a static variable by an object reference like 

myBike.numberOfBicycles

But this is discouraged because it does not tells us that it is a class variable.

Static Methods 
  • It is a method which belong to  the class and not to the object or instance 
  • Static method can access only static data. it can not access non-static data such as instance or variables.
  • static methods can call only  other static variables and not any other non-static variables.
  • A static variable can not  refer to  this or super keyword in anyway.
  •  A static variable can be accessed directly by the class name and do not require any object or instance creation.
  • Syntax : - ClassName.methodName(args)
Example:-

public static int getNumberOfBicycles() {
        return numberOfBicycles;
}


Static methods can be invoked without creating the instance of the class as.in

ClassName.methodName(args)



You can also refer to a static method  like


instanceName.methodName(args) 

But this is discouraged because it does not tells us that the it is a class metho


Static Blocks 

  • Static blocks are the blocks of statement inside a java class that will be executed when a class is first loaded into the JVM.. 
  • This initialization happens even before any instance of the class is created.
Examples:-

class Test{
    static {
        //Code goes here
    }
}


* Note 

Constants 

The static modifiers in combination with the final modifier can also be used to define constants.The final modifier ensures and indicates that the value of the field never changes .

Example:-


static final double PI = 3.141592653589793;



No comments:

Post a Comment