When to use static method and field?

后端 未结 6 781
难免孤独
难免孤独 2020-12-05 22:02

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

6条回答
  •  执笔经年
    2020-12-05 22:23

    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());
    

提交回复
热议问题