1

Suppose the following Java code,

public class ParentClass{
    private parentClass(){}
    public class ChildClass {
        public ChildClass(){}
    }
}

I cannot instantiate the ChildClass like this:

new ParentClass.ChildClass();

This is only possible by making the ChildClass static in Java, whereas it can be done in C# without making it static.

My question is that if the nested class is static then why it can be instantiated in Java and why the same is not possibe in C#. Is the definition of static different for the two languages?

I have seen this stack post, but it does not answer my question.

Community
  • 1
  • 1
Ali Nem
  • 5,252
  • 1
  • 42
  • 41
  • 2
    The use of the `static` modifier in C# and Java just have mean different meanings for types. This is a *language* difference more than a *platform* difference. (There could be another .NET-based language which implements the Java approach, for example.) – Jon Skeet Sep 26 '16 at 11:32

2 Answers2

1

Sounds like a simple syntactic difference to me.

The Java approach is pretty clear: you are accessing static content of ParentClass with ParentClass.ChildClass and then instantiate it with new - new ParentClass.ChildClass();. This means the inner class has to be defined as static, though it's constructor has the regular access.

Until now I did not know about the C# difference you described. I don't use C# much, so, so can't really advocate for this approach.

Boris Schegolev
  • 3,601
  • 5
  • 21
  • 34
0

I finally figured out that the issue is the syntax difference, as @Jon Skeet commented.

The difference is that the static modifier of the nested class (ChildClass in the above example) denotes a static member in Java and does not have the same meaning as the general static class which cannot be instantiated.

Thus, the static modifier in Java does not necessarily prevent instantiating the class it modifies: for a nested static class it allows instantiating and otherwise not. In c#, however, instantiating the static class is always disallowed, whether nested or not, to eliminate the above ambiguity.

I won't accept this answer, however, until I get more feedback from others to see if I am right.

Ali Nem
  • 5,252
  • 1
  • 42
  • 41