A common mistake is (or, hopefully, was) to create a class that contains common static
methods, and then use inheritance to be able to easily access the methods by the classes that require the methods.
So you would have:
class Utility {
static utilityMethod() {
// do something usefull
}
}
class Application extends Utility {
someMethod() {
utilityMethod();
}
}
This however breaks object oriented principles, as ApplicationClass
was never supposed to be a subclass of UtilityClass
. Instead you should use:
final class Utility {
Utility() {
// avoid instantiation
}
static utilityMethod() {
// do something useful
}
}
class Application {
someMethod() {
UtilityClass.utilityMethod();
}
}
Now there are several ways that Java language designers are using to make the above more appealing to use. One is the notion of static imports. The other one is make it feasible for interfaces to have static methods defined on them. In that case the above would become:
import static Utility.utilityMethod;
final interface Utility {
static utilityMethod() {
// do something useful
}
}
class Application {
someMethod() {
utilityMethod();
}
}
Which is a whole lot shorter, especially since most imports are automagically handled by the IDE. Some more discussions/pointers about above can be found here. Note that up to and including Java 7 you cannot declare static methods in an interface.