I know what static is, but just not sure when to use it.
static variable: I only used it for constant fields. Sometimes there are tens of constants in a class, so us
The static field
has one value among all objects and they call it Class member also because it's related to the class.
You can use static filed as a utility.
an example just Assume we need to know how many instances we have :
class Counter
public class Counter {
public static int instanceCount ;
public Counter()
{
instanceCount++;
}
public int getInstanceCount()
{
return instanceCount;
}
}
After creating two instances of Counter
Class. But they share the same instanceCount
field because it's a static field so the value of instanceCount
will become the same in firstCounter
and secondCounter
.
Class main
Counter firstCounter = new Counter();
// will print 1
System.out.println(co.getInstanceCount());
// will print 2
Counter secondCounter = new Counter();
System.out.println(co1.getInstanceCount());