Static classes in C# and Java

Sunday, February 28, 2010


While C# and Java are similar enough that one can often copy/paste code from one to the other with minor changes, sometimes the subtle differences will get you...

Both languages allow you to declare a class as static. They mean very different things, however.

In C#, a static class is pretty straightforward: it is a class with all static members. You can't instantiate a static class.

In Java, it's more complicated. A class can only be marked static if it is an inner class and not anonymous. It is a compile-time error to mark a top-level class as static, e.g. you can't create Hello.java with this as the content:

/* Java */
public static class Hello { /* ... */ }

If an inner class is not declared static, then it can only be instantiated within the context of its enclosing class:

/* Java */
public class Hello { 
    public class Inner {}

    public static void main(String[] args) {
        new Inner(); // compile-time error because there is no enclosing instance of Hello
        new Hello().new Inner(); // ok
        new Hello().createInner(); // ok
    }

    public void createInner() {
        new Inner();
    }
}

If an inner class is declared static, then it behaves as if it was declared as a top-level class:

/* Java */
public class Hello { 
    public static class Inner {}

    public static void main(String[] args) {
        new Inner(); // ok
        new Hello().new Inner(); // can't do this with static class
        new Hello().createInner(); // ok
    }

    public void createInner() {
        new Inner();
    }
}

In C#, there is no equivalent of enclosing instances or non-static inner classes. Inner classes behave the same as top-level classes:

/* C# */
public class Hello {
    public class Inner {} // equivalent to declaring as static in Java
}

Tags: class, csharp, java, static | Posted at 17:06 | Comments (0)


Comments

There are no comments.

Add a comment

Name:
Email: (optional, not displayed to public)
URL: (do not fill this in — leave blank!)

Comment: