Alex Baranosky
Alex Baranosky

Reputation: 50064

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

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. :)

Upvotes: 7

Views: 4048

Answers (4)

Alex
Alex

Reputation: 1

Try this:

public class Util
{
    // final prevents inheritance, just like C# static classes can't be inherited
    // final is basically like the C# sealed keyword.
    public static final class Math
    {
        // prevent constructor from being called
        private Math(){}
        static
        {
            // Acts like a C# static constructor. (only runs once, )
        }
        public static int Add(int num1, int num2)
        {
            return num1+num2;
        }
    }
}

Upvotes: 0

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

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

Upvotes: 9

dweeves
dweeves

Reputation: 5605

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.

Upvotes: -1

Reed Copsey
Reed Copsey

Reputation: 564433

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.

Upvotes: 19

Related Questions