简体   繁体   中英

When to use static method and field?

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 using static constants can save lots of memory. Is there any other typical use cases?

static method: I use it when I make a class about algorithms. For example, a class which provides different sorting algorithms. Is it against OOP design? I think it is better to maintain this way rather than implementing sorting algorithms inside each class that needs to use them. Am I wrong? What are some good use cases?

Also, are there any performance difference between using static and non-static fields/methods?

You are describing cases where you've used static, but this doesn't quite explain fundamentally why you would use static vs non-static - they are more than just keywords for constants and utility methods.

When something is not static (instance), it means that there is an instance of it for each instance of the class. Each one can change independently.

When something is static, it means there is only one copy of it for all instances of the class, so changing it from any location affects all others.

Static variables/methods typically use less memory because there is only one copy of them, regardless of how many instances of the class you have. Statics, when used appropriately, are perfectly fine in object oriented design.

If you have a method/variable that you only need one instance of (eg a constant or a utility method), then just make it static. Understand though that making a method static means it cannot be overridden. So if you have a method you want to override in a subclass, then don't make it static.

The general rule of thumb is - if you need only one copy of it, make it static. If you need a copy per instance, then make it non static.

Is there any other typical use cases?

Global Variables

Is it against OOP design?

Not exaclty, the point is that static methods are stateless since you don't need a particular instance of a class. My favorite approach is for utility methods (like Apache Commons). But you may be aware that some methods may be better placed as class members instead of static.

Also static methods can make class testability harder once you can't override these methods or replace by mock implementation.

Performance difference ?

There's a performance Android recommendation from Google that says "prefer static over virtual":

http://developer.android.com/training/articles/perf-tips.html#PreferStatic

I'm not sure it's true for JVM since Android uses a different VM, but it makes sense given the reasons the link points out:

If you don't need to access an object's fields, make your method static. Invocations will be about 15%-20% faster. It's also good practice, because you can tell from the method signature that calling the method can't alter the object's state."

Static variables belong to a class, hence shared by all the objects, so memory usage is less if you really want the varible to be shared. If you declare the variable as public and static, then it is globally available for everyone.

Static methods are generally the utility methods, depending on the access modifier, those can be used within a class or across the classes. Static utility class will help to reduce the memory usage again because you need not to create the object to call those methods.

My personal rule of thumb is that static things are "just hanging out there". They are things that (disclaimer, not entirely true) are global, but make sense to include with this one particular class.

Static fields are good if you find yourself loading some heavyweight objects repeatedly. For instance, the project I'm working on now has a toggle between two images. These are static fields that are loaded with the application and kept in memory, rather than reloading them every time and letting GC take care of the mess.

Apart from very specific situations, I use static (and final) variables for constants only. It's a totally valid to use them, of course.

I tend to avoid static utility methods, because they make it harder to write unit tests for the code (mocking the results of the method invocation). When you start developing Test Driven way, this issue becomes quite apparent. I prefer using dependency injection and singleton beans (though it depends on your needs and situation).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM