phone: 016-6933793
e-mail: darknessofsorrow@hotmail.com

Saturday 20 October 2012

Static Variables And Static Methods

Static Variables

  1. It is a variable which belongs to the class and not to object. (instance)
  2. Static variable are initialized only once, at the start of the execution. These variables will be initialized first, before the initialization of any instance variables.
  3. A single copy to be shared by all instances of the class.
  4. A static variable can be accessed directly by the class name and does not need any object.
  5. Syntax : <class.name>.<variable.name>


Figure 1 shows an example which sums integers, using static variables. Function sumit() reads a new integer and keeps a cumulative sum of the previous value of the sum and the new integer read in. The cumulative value of sum is kept in the static variable, sum. The driver, main() calls sumit() five times to sum five integers.

Figure 1 : An example for static variable


Static Methods

  1. It is a method which belongs to the class and not to the object. (instance)
  2. A static method can access only static data. It can not access non-static data. (instance variable)
  3. A static method can call only other static methods and can not call a non-static method from it.
  4. A static method can be accessed directly by the class name and does not need any object.
  5. Syntax : <class.name>.<method.name>
  6. A static method can not refer to "this" or "super" keyword in anyway.


Figure 2 shows a declaration of static method




0 comments: