In addition, are there any performance advantages to static methods over instance methods?
I came across the following recently: http://www.cafeaulait.org/course/week4/22.html :
When should a method be static?
- Neither reads from nor writes to instance fields
- Independent of the state of the object
- Mathematical methods that accept arguments, apply an algorithm to those arguments, and return a value
- Factory methods that serve in lieu of constructors
I would be very interested in the feedback of the Stack Overflow community on this.
Sometimes a method or class is used a lot throughout your project that you don't want to make a lot of instances of it, so you just make it static.
A static method can access only static members and can not access non-static members. A non-static method can access both static as well as non-static members. Static method uses complie time binding or early binding. Non-static method uses run time binding or dynamic binding.
Make methods static when they are not part of the instance. Don't sweat the micro-optimisations.
You might find you have lots of private methods that could be static but you always call from instance methods (or each other). In that case it doesn't really matter that much. However, if you want to actually be able to test your code, and perhaps use it from elsewhere, you might want to consider making those static methods in a different, non-instantiable class.
Whether or not a method is static is more of a design consideration than one of efficiency. A static method belongs to a class, where a non-static method belongs to an object. If you had a Math class, you might have a few static methods to deal with addition and subtraction because these are concepts associated with Math. However, if you had a Car class, you might have a few non-static methods to change gears and steer, because those are associated with a specific car, and not the concept of cars in general.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With