java - How can utility classes be used to group methods on a final class, instead of extending the class? -


joshua bloch mentions in book (effective java - 2nd ed) in item 4 :-

classes containing static fields , static methods (utility classes) can used group methods on final class, instead of extending class.

can explain sentence?

a common mistake (or, hopefully, was) create class contains common static methods, , use inheritance able access methods classes require methods.

so have:

class utility {     static utilitymethod() {         // usefull     } }  class application extends utility {     somemethod() {         utilitymethod();     } } 

this breaks object oriented principles, applicationclass was never supposed subclass of utilityclass. instead should use:

final class utility {     utility() {         // avoid instantiation     }      static utilitymethod() {         // useful     } }  class application {     somemethod() {         utilityclass.utilitymethod();     } } 

now there several ways java language designers using make above more appealing use. 1 notion of static imports. other 1 make feasible interfaces have static methods defined on them. in case above become:

import static utility.utilitymethod;  final interface utility {     static utilitymethod() {         // useful     } }  class application {     somemethod() {         utilitymethod();     } } 

which whole lot shorter, since imports automagically handled ide. more discussions/pointers above can found here. note , including java 7 cannot declare static methods in interface.


Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

java - Using an Integer ArrayList in Android -