Static vs. non-static method

前端 未结 10 1122
执念已碎
执念已碎 2020-11-28 08:30

Suppose you have some method that could be made static, inside a non-static class.
For example:

private double power(double a, double b)
    {
        r         


        
10条回答
  •  再見小時候
    2020-11-28 09:32

    this method should be static because it is not related to your class or member of classes. it just works with the inputs to this function.

    maybe you may need to call it without creating that class. so if it is static it is ok but if it is not, you cant call it without any instance of that class.


    Advantages of a static method:

    There's no need to create an object first. The method is available immediately.

    It's a good when you have generic functionality that does not depend on the state of a particular object. For example, look at the Arrays class or the Collections class from java.util.

    Static methods can be good for factories. Pass your requirements as parameters, get a brand new object back. Not a constructor in sight.

    Disadvantages of a static method:

    You don't have an object instance, so you only have access to static members and your own local variables. If you want an instance, you probably have to create it yourself.

    You can create subclasses, but a static method can't be abstract, so it's harder to decouple your implementation from a caller.


    (ps: i dont think compiler will optimize if it is going to be static or not.. but not sure)

提交回复
热议问题