2

Joshua Bloch mentions in his book (Effective Java - 2nd Ed) in Item 4 :-

Classes containing just static fields and static methods (utility classes) can be used to group methods on a final class, instead of extending the class.

Can anyone explain this sentence?

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
user1522820
  • 1,584
  • 5
  • 18
  • 31

1 Answers1

1

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.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263