As per my understanding we should go for instance methods only when they are dealing with state of object i.e instance variable . If method does deal with state of object they should always be declared as class methods i.e static. But still in most of the projects i ihave seen the methods which never not operates on instance variables they are also declared as instance methods(basically what these methods are doing they are using some of the method parametrs and doing some processing on that paremets and calling some other classes).Thats it. Should not these methods should be declared as class method i.e static ?
Instance method vs Static methodInstance method can access static variables and static methods directly. Static methods can access the static variables and static methods directly. Static methods can't access instance methods and instance variables directly. They must use reference to object.
They are faster — Static methods are slightly faster than instance methods because in instance methods, you are also working with an implicit this parameter. Eliminating that parameter gives a slight performance boost in most programming languages.
Also static methods exist as a single copy for a class while instance methods exist as multiple copies depending on the number of instances created for that particular class. Static methods can't access instance methods/variables directly while instance methods can access static variables and static methods directly.
Static methods can be called without the object of the class. Instance methods require an object of the class. Static methods are associated with the class. Instance methods are associated with the objects.
It's likely the answer is yes: if you have an instance method that doesn't actually take advantage of the instance state, then it should probably be static
, and possibly moved to a helper class depending on what it does.
Note that even if you don't access instance variables, accessing instance methods will also disqualify a method from becoming static
. Also, if this method is an instance method in order to future-proof it (in anticipation of using the instance state later,) then changing it wouldn't be advisable either.
Also important is that public non-static methods could be inherited and overriden by a subclass, so making them static
could actually break the code in possibly unexpected ways.
Here's a [possibly incomplete] list when you must use instance methods over static ones:
synchronized
and don't want to lock on the class, rather on the instanceYou could probably go static in all other cases.
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