Editor's note: Sometimes the most interesting discussions begin when someone says, "This may be a stupid question, but ...". If the person asking the question has taken the time to think about the problem before asking, the question is often not stupid at all. The uncertainty points out an ambiguity in the specs, holes in the docs, or a search for how more experienced programmers might address a particular problem. From time to time, we will print one of the "(Not So) Stupid Questions" we receive and invite our readers to answer the question in the feedback section.
Remember that new people are joining the Java community all the time and may be looking for help from those with more experience. Also, those who began with Java as their first language can benefit from those coming to the community with experience in other languages. As always, answer the questions with kindness. You are also welcome to submit your questions to
This may be a stupid question, but ... "Should I try to declare more of my methods to be static?"
I was recently reading "Item 8: Always override hashCode when you override equals" in Joshua Bloch's book Effective Java. Notice that the rangeCheck() method is static in the following code listing from that item.
public final class PhoneNumber {
private final short areaCode;
private final short exchange;
private final short extension;
public PhoneNumber(int areaCode, int exchange, int extension) {
rangeCheck(areaCode, 999, "area code");
rangeCheck(exchange, 999, "exchange");
rangeCheck(extension, 9999, "extension");
this.areaCode = (short) areaCode;
this.exchange = (short) exchange;
this.extension = (short) extension;
}
private static void rangeCheck( int arg, int max, String name) {
if (arg < 0 || arg > max )
throw new IllegalArgumentException(name +": " + arg);
}
public boolean equals(Object o) {
if (o== this)
return true;
if (!(o instanceof PhoneNumber))
return false;
PhoneNumber pn = (PhoneNumber)o;
return pn.extension == extension &&
pn.exchange == exchange &&
pn.areaCode == areaCode;
}
// Remainder omitted
}
The rangeCheck() method does not depend on any instance variables, so the method could have been declared static or not. On the other hand, the equals() method depends on the values of the extension, exchange, and areaCode variables. The equals() method could not be static unless those three variables were all static, and then you would have one single phone number shared by all instances of the PhoneNumber class.
So I think it is clear when a method can not be static. My question is,
When a method can go either way, when should you make it static and when should it belong to the object?
It seems that, at least when we teach Java newcomers, we do not encourage them to consider static methods (other than main()), and we introduce the concept with static variables that are often used as constants.
(Not So) Stupid Questions is where we feature the questions you want to ask but aren't sure how.
how can a static method get the object reference of the calling object?
2008-04-15 05:06:12 lalitkamal
[Reply | View]
can we find out if there is any way that the static method named as statMethod() can get the object reference of the calling object in the following example?
Note: both print statement should print the same value.
Basically i need to find out what the code XXXXX should be so that obj gets the same value as "this" of Class ABC.
eg:
public class ABC {
Main()
{
system.out.println(this);
XYZ.statMethod();
}
}
class XYZ {
public static statMethod() // no arguments
{
Object obj;
obj = XXXXX; // what shoul i write here.
system.out.println(obj);
}
}
Util Class should be the way
2004-01-11 16:57:27 izy100
[Reply | View]
public static void rangeCheck( int arg, int min, int max, String name) {
if (arg < min || arg > max )
throw new IllegalArgumentException(name +": " + arg + " is out of range");
}
I'll mostly likely have a util class and have the checkRange method as above to be generic and more reusable by other classes.
Bind the method to the object in question
2004-01-06 06:40:29 gregsmith
[Reply | View]
if you think of a class as a proper object, then making a method static or not is simple. the static variables and methods belong to the class while the non-static variables and methods belong to the instance.
a method should be bound to the class (made static) if the method operates on the class's static variables (modifies the class's state). an instance object should not directly modify the state of the class.
a method should be bound to the instance (made non-static) if it operates on the instance's (non-static) variables.
you should not modify the state of the class object (the static variables) within the instance (non-static) method - rather, relegate that to the class's methods.
although it is permitted, i do not access the static methods through an instance object. i only access static methods through the class object for clarity.
and since the instance variables are not part of the class object itself, the language cannot and does not allow access to non-static variables and methods through the class object's methods.
Bind the method to the object in question
2004-01-06 06:49:50 gregsmith
[Reply | View]
to answer the case in point ...
in the case where neither class nor instance variables are accessed, one should determine if the method "operates" on the class or the instance. if it operates on the class, then make it static (associate it with the class), else make it non-static.
In the example, this is a simple utility function. Arguably, it does not even belong in this class since it does not operate on either the class or the instance. as such i would make it a static method.
in practice, i relegate such methods to a more general Util class - where all methods are static. I often have a different Util class in each package.
Look at the real problem
2004-01-02 04:49:23 stephendevelop
[Reply | View]
The fact that your method does not use any fields of the class indicates that it is not in its place.
This method is more general, it can be used in a number of different places.
Consider putting all the related general methods in one class and name it accordingly.
It is more easy if you think of the Single Responsibility Principle of Agile Software Development. If the logic of a utility method needs to change, it is unlogically that a class called TelephoneNumber or something like that needs to change
Simple what to know???
2004-01-01 15:31:26 staypufd
[Reply | View]
What I teach people is that static methods are those methods that have a contextual environment of the class, thus those methods which include the constructor, only have access to those variables that are declared static and/or are passed in to the constructor. Static methods are thus what other OO languages would call class methods.
I also try to teach them to lay out class definitions with the static variables and methods at the top, then the instance variables and methods at the bottom.
I think this leads to a clearer understanding of them and there proper usage, especially in light of the fact that classes are objects in Java.
Simple what to know???
2004-01-13 04:56:04 diegof79
[Reply | View]
> I think this leads to a clearer understanding of them and there proper usage, especially in light of the fact that classes are objects in Java.
Classes are not "pure" objects in Java, and a static method is not a class method like in Smalltalk.
For example you can't sub-class an static method... and if a class is an object, what is the class of a class? (look for some texts about meta classes in smalltalk to clarify my point)
What many dont understand
2004-01-01 10:00:37 zander
[Reply | View]
What is much misunderstood about static methods is that its impossible to extend them. Extending a class and overwriting a method can not be done with statics.
So if your class stands a change of being extended (OO still stands for reusability) and someone _might_ want to make the method do something a little different its a good choice to not make the method static.
On the whole it depends on if the method does something to the object or is only partly relevant to the object. In the latter case you want a static.
Can 'static' Reduce the Memory Footprint of an Object?
2003-12-31 12:23:24 wthomp6984
[Reply | View]
My personal use of 'static' is related to the method's applicability outside of an instance of the class. However, I was wondering if declaring a method 'static' would impact the memory footprint of an instance of that class.
In a memory constrained environment, possibly an RTSJ based project, does it make sense to use 'static' on a method that does not access member variables in order to reduce the overall footprint of a particular object?
Can 'static' Reduce the Memory Footprint of an Object?
2004-01-01 04:29:13 heaththegreat
[Reply | View]
well, technically, all methods are static. the class represents all methods as static methods, but the instance methods simply pass a reference to the class itself as an implied variable. So, it makes no impact on memory other than the fact that you are effectively passing one additionaly argument to your method. Its not really anything to get twisted up about.
Static Methods are Simpler and Easier to Understand
2003-12-30 20:37:54 marc_
[Reply | View]
I have to admit that I long ago formed the habit of always using the 'static' modifier if the method didn't depend on an instance of its enclosing class. Joshua Bloch's book advises against using non-static member classes, so I'm surprised it doesn't also warn against non-static methods for similar reasons.
When I see the 'static' keyword I can immediately relax knowing that all the variables are declared and set right in front of me - I don't have to go digging around in the class (or superclass) to see where a variable is defined and (possibly elsewhere) where it has been set. Without the 'static' it would take a little longer before the penny dropped.
To get a little philosophical, it's also a question of information hiding. If a component (method, class, package) doesn't need something, it shouldn't be given access to it.
Also if the method is part of a published API, you will force users to instantiate the class just to call the method - inefficient and ugly. If later your method needs access to instance fields, you are probably changing the meaning of the method and should instead declare another one.
One last point: I'm talking here about methods whose MEANING (not just the code) is independant of the class instance. For example this shouldn't be static:
/**
* Returns the width of the object
*/
public int getWidth() {
return 300;
}
... but this should:
/**
* Throws an IllegalArgumentException if arg isn't
* between 0 and max, inclusive
*/
private static void rangeCheck( int arg, int max, String name) {
if (arg < 0 || arg > max )
throw new IllegalArgumentException(name +": " + arg);
}
Static Methods are Simpler and Easier to Understand
2003-12-30 20:55:44 ronaldtm
[Reply | View]
"I don't have to go digging around in the class (or superclass) to see where a variable is defined and (possibly elsewhere) where it has been set."
Well, assuming it doesn't access any static variable...
"Also if the method is part of a published API, you will force users to instantiate the class just to call the method - inefficient and ugly."
And if you use static methods, you force users to create dependances to a specific class. By using a non-static method, one can override it, increasing its flexibiility.
Common rule - when you do not know what kind of access the method should be assigned to - is to be as much restrictive as you can.
For example, you should consider making the method protected only if it CANNOT be left private.
In that sense a private not-static method is more restrictive than a private static as having an instance of the class is definetely more restrictive than not having one.
Happy New Year from New York !
This only works for classes that should not be extended; if your class could be extended changes are your policy will make one-too-many method private making it impossible to change small things without copying lots of code.
The designer of the class must cleary state which method can be extended by marking the method protected. If it is private then you are not supposed to override the method.
Let's try it out
2003-12-30 07:59:58 jt2190
[Reply | View]
What happens when we call this code? The method is private so it will only be used in instances of PhoneNumber.
rangeCheck( areaCode, 999, "areaCode" );
Of course, we are supposed to identify the method as static by appending the class name on the front. Also, if the method weren't private, we would call it from other classes like this.
So, assuming that another programmer is reading this code for the first time, which version makes your intent more explicit? I know which one I like, but I'm not saying! :)
Let's try it out
2003-12-30 21:26:08 ronaldtm
[Reply | View]
... and you initialize it once, and eliminate those repeated parameters.
Non-static methods add more flexibility to the code (at the cost of initializing it). In classes such as Math, it doesn't make sense to configure it, but sometimes it is really useful.
Let's try it out
2004-01-12 08:40:58 captain_object
[Reply | View]
I think that's quite a good example - in fact, the rangeCheck method is not really well placed in the PhoneNumber class. And that's why it is hard to decide whether to make it static or not.
If it is factored out into a dedicated Checker class, all of a sudden it is clear that it has to be non-static, because it is the main task for a Checker to do checks.
What the rangeCheck method does has nothing to do with the domain of the PhoneNumber class. So - as already suggested in earlier comments - it would be best to put it into a common utility class or a special class for doing this kind of checks.
My opinion about static/non-static decisions is, that if you follow a hard-line OO approach, everything falls into place almost by itself.
Static methods are almost everytime utility methods. They are not really object oriented, because in Java, classes are no first-class objects. Static Java methods are not made for polymorphism. They are most of the time convenience methods.
As a provoker, I say: Extensive declaration of static variables and methods is a good sign for bad design.
Static methods can be useful, but often you will find they pin you into a corner. To a new developer switching from 'C' or VB, they seem to make Java familiar. But Java is not a procedural language, nor should it be used as such.
I worked on a project once where all the methods were static, the designer thought he had uncovered a great new tool to build with (this was in 1998), he was wrong. It was the most warped 2meg pile of applet code I've ever worked with.
Recently a guy that I'm tutoring for the Java Cert brought me a sample program he wrote. His use of static, meant that he was passing in instances of the class he was calling the method from, or it's variable to work with them. So much wasted code, time, and memory. Be OO is new to him and it made things easier to follow, but the code was harder too read (eg. x.compare(x,y); // why pass x? I already have access to it).
Now I'm not saying that statics are all bad, there are times when they can help and times when they are more trouble than they are worth.
Think of the Math class. All methods are static, because you use them on other objects of various types, and to add this code to the Numbers class would bloat out systems that may never use .abs(), .floor(), etc. The example code you included uses a static in a good way. There are 3 different ways they use it. To replicate this in a non-static form, you might end up with 3 more methods that setup the range variables to call this method, or pass in some CONST and then use a switch/case statement to select the information you are checking. (Bingo, a red flag should have popped up when I said that.) switch/case to select information is a bad design technique for OO. The 3 method way just clutters your code, thus leaving static as a good alternative. (however there are usually 5 ways of doing anything, and we have just touched on 3, so there are 2 more, and one of those way may be more elegant but for a lack of time I can't pull them out of my head just right now;).
My rule on statics (and it's my rule, so if you don't like it make up your own) if it keeps your class more OO-ish, and reduces clutter or complexity, then it's a good use. Start out with other options and only go to statics when absolutely needed.