Leandro Coutinho wrote:static methods can't access instance variables
John Robert wrote:... my question was, is that the criteria to determine if a method should be declared static or not.
SCJP 5 | SCWCD 5
[How to ask questions] [Twitter]
, hence if your method doesn't need to manipulate instance variables it can be static.Leandro Coutinho wrote:static methods can't access instance variables
John Robert wrote:Ranchers,
I know a static method is a part of a class as opposed to the object. But my dilemma is when i put a method as part of a class, when should i declare it as static, and when should i declare it non static. Here is my theory please correct me if i am wrong, if the method is accessing any of the instance variables(which effect the state of the object) , then declare method non static. Else declare static. Am I correct?
That looks like a spelling error, Ernest. Surely it's "access to instance data"?Ernest Friedman-Hill wrote:Hi John,
Not needing access to static data is one criterion for allowing a method to be static. . . .
uj nossnahoj wrote:
A good rule of thumb is that you make the method non-static as a first approximation. You'll quickly discover whether this was the wrong choice because then you cannot use the method the way you intended. Then you change to static.
Campbell Ritchie wrote:Disagree. Only make something "static" when you have a good reason to. Always try non-static first.
Ernest Friedman-Hill wrote:Hi John,
Not needing access to static data is one criterion for allowing a method to be static. I'd add three more requirements even given thids first criterion is met.
2) Methods that might need to be replaced or stubbed out during testing. If a class has a method called "queryDatabase()", during testing you might want to write a subclass that overrides queryDatabase() to just return some canned data. If the method is static, you can't do that. If you're new to programming, you might not appreciate this last point, but it's very important.
So actually, that leaves only a few kinds of methods that really should be static. The methods in java.lang.Math that return the square root, absolute value, etc, are great examples. They're all concentrated in one class, and you'd never want to change their behavior. The default should always be instance methods; static methods are a fairly rare exception.
John Robert wrote:I actually was thinking the other way around, my theory was, first try to see if static woks for a method, if it does then do static, because from a efficiency/memory perspective you will not need to instantiate the class to call this method. May be I am wrong, I am not sure.
Consider Paul's rocket mass heater. |