Originally posted by Nick Delauney:
Hello all,
My Question is in regards to what is happening when there is a new instantiation in a static method. The object is not created when the class is referenced, is it ?
example
class StaticUtil
{
public static aMethod()
{
ArrayList al = new ArrayList();
// some code
}
}
The ArrayList will not be created until the StaticUtil.aMethod() is called. static only means that this method does not need to be invoked on an object of the class. Note that multiple calls to your aMethod() will create multiple ArrayLists. The static nature of the method does not mean there is only one 'al'.
2) Should all methods of a utility class be static ?
I'm not sure what kind of
utility class you're thinking about, an example might help. But, in general, I prefer to not have just static methods in a class. I think that having instantiable objects is preferable to calling static methods on a class. Since I'm not that familiar with the
Java class library, there may be an idiom for certain cases. I'd like to see how other people respond to this question.
3) Is it true interfaces cannot have static methods, why not ?
Interfaces represent abstract functionality that must be implemented by the classes that implement that functionality. Static methods can't be overriden, so they can't be abstract [and all methods in an interface are abstract].