Introduction to Static Keyword
Ordinarily, when you create a class you are describing how objects of that class look and how they will behave. You don’t actually get anything until you create an object of that class with new, and at that point data storage is created and methods become available.
But there are two situations in which this approach is not sufficient. One is if you want to have only one piece of storage for a particular piece of data, regardless of how many objects are created, or even if no objects are created. The other is if you need a method that isn’t associated with any particular object of this class. That is, you need a method that you can call even if no objects are created. You can achieve both of these effects with the static keyword. When you say something is static, it means that data or method is not tied to any particular object instance of that class. So even if you’ve never created an object of that class you can call a static method or access a piece of static data. With ordinary, non-static data and methods you must create an object and use that object to access the data or method, since non-static data and methods must know the particular object they are working with. Of course, since static methods don’t need any objects to be created before they are used, they cannot directly access non-static members or methods by simply calling those other members without referring to a named object (since non-static members and methods must be tied to a particular object).
All objects refer to the same piece of memory so they share same value of data members. An important use of static for data members and methods is to allow you to call that data member or method without creating an object.
Syntax
class Test {
static int i = 47;
}
To make a data member or method static, you simply place the keyword before the definition.
Example
1. /**
2. * @(#)StaticDemo.java
3. *
4. *
5. * @author
6. * @version 1.00 2009/11/17
7. */
8.
9. class Example {
10.
11. static int i = 50;
12.
13. }
14.
15. public class StaticDemo {
16.
17. /**
18. * Creates a new instance of StaticDemo.
19. */
20. public StaticDemo() {
21. }
22.
23.
24. static public int incr() {
25.
26. Example.i++;
27.
28. return Example.i;
29.
30. }
31.
32. /**
33. * @param args the command line arguments
34. */
35. public static void main(String[] args) {
36. // TODO code application logic here
37.
38. StaticDemo obj = new StaticDemo();
39.
40. int val = obj.incr();
41.
42. System.out.println("Incremented value is: " + val);
43.
44.
45. }
46. }
Output
Incremented value is: 51
The static data members and methods can be accessed directly by their class name or using object of the class.
