Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

When to make a class holding state static?

 
A Ba
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1561
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are no stand-alone "static" classes in Java.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
Shanky Sohar
Ranch Hand
Posts: 1051
Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Vijitha Kumara
Bartender
Posts: 3914
9
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Shanky Sohar
Ranch Hand
Posts: 1051
Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic