• Post Reply Bookmark Topic Watch Topic
  • New Topic

Significance of private static method  RSS feed

 
Tom Clancy
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have seen private static methods being used in practice. Can anyone please explain why it is used?
[ June 04, 2004: Message edited by: Tom Clancy ]
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Two use cases I can think of offhand:
  • Helper methods that need to be called from a static context, e.g. a public static method.
  • Methods that manage some static resource on behalf of class instances, e.g. they encapsulate some static variable that is accessed by instances of the class through the private static method.
  • - Peter
     
    Dirk Schreckmann
    Sheriff
    Posts: 7023
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Moving this to the Intermediate forum, as it's not specific to the SCJP test...
     
    sever oon
    Ranch Hand
    Posts: 268
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    The reason one might mark a method private aren't any different just because the method also happens to be static, and vice versa. One thing I'll oftentimes do is write getter and setter methods for a particular property, and then if I want that property to be immutable I'll mark the setter private. This seems to me a perfectly valid thing to do because it still creates a single point of modifying the value of that property internally, even if it's only done from a constructor. If that variable happens to be static, then the getters and setters are too, and if it happens to be immutable or only settable from within the class itself, the setter would be both static and private.

    I'll admit, this is a rarity for me though. Generally I eschew private methods because if I'm using a lot of them, that probably means that the class is doing something complicated enough that it should be broken into one or more aggregated classes. There is one case where I've found the static private method to be indispensable, though:



    Now, let me set up the situation. I want to extend Foo with a subclass called Bar. Bar has a constructor that takes some kind of character reader, reads all of the content from it into a StringBuffer, and then initializes the superclass Foo's xyz property with the result of that buffer.

    The problem: the first line of Bar's constructor must be a call to super. There is no way to do all of that processing on a reader, get the content into a string buffer, and then get the string out of the string buffer and into super(). Unless...you capture all that logic in a private static method:



    sev
     
    Consider Paul's rocket mass heater.
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!