aspose file tools*
The moose likes Beginning Java and the fly likes When to make a class holding state static? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "When to make a class holding state static?" Watch "When to make a class holding state static?" New topic
Author

When to make a class holding state static?

A Ba
Greenhorn

Joined: Sep 24, 2010
Posts: 1
Hi,

I am a fairly experienced C# coder, but new to Java. My question is a general programming question:

- Usually a class which has no internal state (ie fields) is a good candidate for being made static (So doesn't change its reciever class). However, is there ever a reason to make a class holding internal state (fields) a static class? Any examples?

Thanks
pete stein
Bartender

Joined: Feb 23, 2007
Posts: 1561
There are no stand-alone "static" classes in Java.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

The C# "static class" concept isn't a first-class concept in Java; i.e, there's no way to explicitly declare one, and the idea isn't used much in Java (you can emulate one by giving your class only a private constructor and then never using it.) Frankly, it's just a mechanism for writing in a non-object-oriented style, and used only in fairly obscure cases like the java.lang.Math class, which holds a bunch of trignonometric and other free math functions. Classes like this lead to brittle, nonmodular code that's hard to test.

So my answer to your question is "no" -- there's never a good reason to do that. Put the state into instance methods, and make the methods instance methods, and that's that!


[Jess in Action][AskingGoodQuestions]
Shanky Sohar
Ranch Hand

Joined: Mar 17, 2010
Posts: 1051

Welcome to JavaRanch.
Static keyword with outer class is used more rarely in java,and in most of the time used with inner classes.
which you got to know once you studied inner classes


SCJP6.0,My blog Ranchers from Delhi
Vijitha Kumara
Bartender

Joined: Mar 24, 2008
Posts: 3825

Shanky Sohar wrote:Static keyword with outer class is used more rarely in java...

In fact it is not allowed at all as pointed out earlier.


SCJP 5 | SCWCD 5
[How to ask questions] [Twitter]
Shanky Sohar
Ranch Hand

Joined: Mar 17, 2010
Posts: 1051

Oh yes.how can it skip from my mind that it is not applied to outer class
for outer class only public,abstract and final is permitted.......

Thanks for pointed out the mistake from my Quote
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: When to make a class holding state static?