This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "static modifier" Watch "static modifier" New topic
Author

static modifier

Allen Springers
Greenhorn

Joined: Oct 23, 2007
Posts: 4
Hi
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?

Thanks
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

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

No.

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
sscce.org
Jim Yingst
Wanderer
Sheriff

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: http://aspose.com/file-tools
 
subject: static modifier
 
Similar Threads
why cant the output of the code is 2
Using enum in remote object
Static method modifier question
Access Specifiers vs Access Modifiers
Error in Tomcat