tags:

views:

144

answers:

3

Do they have the equivalent of C# static classes in Java?

I want to create a C# static class but in Java, how do I do it?

Thanks for the help.

EDIT: Thanks for the help guys. :)

+5  A: 

No. Just mark everything static. Possibly add a private constructor that throws an error and make the class final.

Tom Hawtin - tackline
I've never tried this, but what happens if you try to mark the class as final and abstract?
R. Bemrose
It can't be both `final` and `abstract`, unfortunately. But good point.
Tom Hawtin - tackline
You'd get a compile time error.
RichardOD
Interesting note: C# static classes are abstract and sealed. No need for a private constructor.
Snarfblam
@Snarfblam: And the compiler stops you from trying to use it as if you could ever have an instance (e.g. you can't use it as a parameter type). No such benefits in Java, unfortunately :(
Jon Skeet
Prefer this to the accepted answer just coz of the additional detail on final and private constructor.
serg10
+8  A: 

There are static members in Java classes, but no static class, like in C#.

The C# static class modifier doesn't really change anything about the class, from a usage standpoint, though. It just prevents you, at compile time, from adding instance variables.

You can make a class in Java that would work like a C# static class by just declaring every member as static. See the tutorial section on "Understanding Instance and Class Members" for details.

Reed Copsey
Yeap in .NET 1.1 I remember creating a sealed class with a private constructor to achieve the desired effect.
RichardOD
It also prevents you at compile time from adding instance methods, operator overloads or `new` expressions that would allocate an instance of the class.
Daniel Earwicker
+1  A: 

In every OO language,a good (an more flexible) alternative to static class declaration is to use the singleton pattern.

However, if your class is a pure utility class, you can declare all your members/methods as static.

dweeves
A singleton just makes it more difficult to use.
Tom Hawtin - tackline
if the solution to a problem is to add a singleton, now you've got two problems...
Rich Seller