Calling class staticmethod within the class body?

When I attempt to use a static method from within the body of the class, and define the static method using the built-in staticmethod function as a decorator, like this: class Klass(object): @staticmethod # use as decorator def _stat_func(): return 42 _ANS = _stat_func() # call the staticmethod def method(self): ret = Klass._stat_func() + Klass._ANS … Read more

Should private helper methods be static if they can be static

Let’s say I have a class designed to be instantiated. I have several private “helper” methods inside the class that do not require access to any of the class members, and operate solely on their arguments, returning a result. public class Example { private Something member; public double compute() { double total = 0; total … Read more

Namespace + functions versus static methods on a class

Let’s say I have, or am going to write, a set of related functions. Let’s say they’re math-related. Organizationally, should I: Write these functions and put them in my MyMath namespace and refer to them via MyMath::XYZ() Create a class called MyMath and make these methods static and refer to the similarly MyMath::XYZ() Why would … Read more

How to call getClass() from a static method in Java?

I have a class that must have some static methods. Inside these static methods I need to call the method getClass() to make the following call: public static void startMusic() { URL songPath = getClass().getClassLoader().getResource(“background.midi”); } However Eclipse tells me: Cannot make a static reference to the non-static method getClass() from the type Object What … Read more

Why can’t I define a static method in a Java interface?

EDIT: As of Java 8, static methods are now allowed in interfaces. Here’s the example: public interface IXMLizable<T> { static T newInstanceFromXML(Element e); Element toXMLElement(); } Of course this won’t work. But why not? One of the possible issues would be, what happens when you call: IXMLizable.newInstanceFromXML(e); In this case, I think it should just … Read more

Why doesn’t Java allow overriding of static methods?

Why is it not possible to override static methods? If possible, please use an example. 22 s 22 Overriding depends on having an instance of a class. The point of polymorphism is that you can subclass a class and the objects implementing those subclasses will have different behaviors for the same methods defined in the … Read more