Class Methods/Static Methods
Suppose you need a value that will always be the same (but not fixed) for all objects of that class. If you had to do it with the knowledge you gathered on OOP till now, you might try to keep track of all the objects in an array and keep a property constant for all the objects when one object changes the value.
However, this approach is very tedious and not efficient at all. Most of the OOP-supported languages will give you the convenience of a static
keyword. A static property or method is "static" to all the objects. Only one unit of memory will be allocated for a class so that it can be accessed from the class and all of its instances. All the objects of that class will be sharing this single value.
There are a lot of usages for static attributes and methods of a class. For example, we can keep a count of the number of instances created from that class by maintaining a static count
attribute. This cannot be done with a normal attribute since it would be reset when a new object is created, plus all instances would have their own value for each attribute (which is not desired).
1// ObjectCounter.java
2public class ObjectCounter {
3 private static int count = 0;
4
5 // Note: we cannot access static attributes with this keyword
6 public ObjectCounter() { count++; }
7
8 // all methods using static attribute or method will need to be static
9 public static int getCount() {
10 return count;
11 }
12
13 public void finalize() { count--; }
14}
15
16// Main.java
17public class Main {
18 public static void main(String[] args) {
19 // Static attributes/methods can be accessed from the class
20 System.out.println(ObjectCounter.getCount()); // 0
21
22 ObjectCounter obj = new ObjectCounter();
23 ObjectCounter obj2 = new ObjectCounter();
24 ObjectCounter obj3 = new ObjectCounter();
25
26 System.out.println(ObjectCounter.getCount()); // 3
27
28 // This is the way to cleanly delete an object before scope in java
29 obj.finalize(); obj = null;
30 obj2.finalize(); obj2 = null;
31
32 System.out.println(ObjectCounter.getCount()); // 2
33 }
34}