Static or non-static method? I have utility methods in a class. Some methods are used by a few classes and some are used by many classes. I am not sure if I should make them static or not static. Does it matter? Does this affect performance or resource use? Thanks.
BJ - SCJP and SCWCD
We love Java programming. It is contagious, very cool, and lot of fun. - Peter Coad, Java Design
1. As far as I understand it, declaring a method static or non-static has something to do more with the abstracted behavior of that class from the "real thing" in the problem domain, as opposed to the expectation that it will be used by many/few classes. 2. Also "Premature optimization is the root of all evil" as Donald Knuth used to say. Optimize later. [ September 19, 2002: Message edited by: Anthony Villanueva ]
Joined: Sep 20, 2001
A method should be static if it doesn't need a "this" object--that is, if it doesn't refer to any object instance variables.
How about if the methods are in separate class? In this case static or non-static, they don’t reference instance variables of the calling class. Thanks. [ September 19, 2002: Message edited by: Bruce Jin ]
Maybe this will help. From a 3/99 JavaWorld article:
Methods that don't manipulate or use the state of an object or class I call "utility methods." Utility methods merely return some value (or values) calculated solely from data passed to the method as parameters. You should make such methods static and place them in the class most closely related to the service the method provides. An example of a utility method is the String copyValueOf(char data) method of class String. This method produces its output, a return value of type String, solely from its input parameter, an array of chars. Because copyValueOf() neither uses nor affects the state of any object or class, it is a utility method. And, like all utility methods should be, copyValueOf() is a class method. So one of the main ways to use class methods is as utility methods -- methods that return output calculated solely from input parameters. Other uses of class methods involve class variables.
Also, when appropriate, you do save some resources by using static methods/fields because the weight of each object instance that is created is smaller because those methods/fields are "owned" only by the class and not each instance.
Blake Minghelli<br />SCWCD<br /> <br />"I'd put a quote here but I'm a non-conformist"