File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes static modifier Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "static modifier" Watch "static modifier" New topic

static modifier

Allen Springers

Joined: Oct 23, 2007
Posts: 4
I am just wondering, if I am not sure what modifier to use for my member functions, should I always use "public static" modifier?

I read a book, it says that it's always better to use factory method. So I set my defult constructor to private and create a public static getInstance function for creating objects. Is it true?

marc weber

Joined: Aug 31, 2004
Posts: 11343

Originally posted by Allen Springers:
...should I always use "public static" modifier? ...


For one thing, static methods cannot be overridden, so this would prevent you from using polymorphism, which is a critical feature of Object Oriented Programming.

Did this book say why it's "always better"? And does it make sense that this reason will always apply? In general, never say "always."

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
In choosing between public and private (or protected or default) I recommend that any time you're not sure, use private. If you get a compile error, then you will immediately know that there's a reason why it can't be private. But in general, it's easier to change a declaration from private to public than to change it from public to private. So when in doubt, try private, and you can easily make it public later if you need to.

For static vs. non-static, it's harder to say. If you need to use any nonstatic member data, the n you can't make the method static. But if you don't need nonstatic data, it still may be beneficial to use a nonstatic method, in order to take advantage of polymorphism. Basically, if you think you might need more than one implementation of a method for different situations, then it's probably a good idea to make the method nonstatic. But if you're pretty confident that you will only ever need one implementation, then you might as well make the method static, as it will usually be easier to use.

"I'm not back." - Bill Harding, Twister
I agree. Here's the link:
subject: static modifier
It's not a secret anymore!