Static Variables And Static Methods
Static Variables
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.
Static Methods
Figure 2 shows a declaration of static method
- It is a variable which belongs to the class and not to object. (instance)
- 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.
- A single copy to be shared by all instances of the class.
- A static variable can be accessed directly by the class name and does not need any object.
- 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
- It is a method which belongs to the class and not to the object. (instance)
- A static method can access only static data. It can not access non-static data. (instance variable)
- A static method can call only other static methods and can not call a non-static method from it.
- A static method can be accessed directly by the class name and does not need any object.
- Syntax : <class.name>.<method.name>
- A static method can not refer to "this" or "super" keyword in anyway.
Figure 2 shows a declaration of static method
0 comments: