Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

public inner classes

Tags:

java

c#

.net

Can anyone explain, why we can do such thing and why we need this

public class OuterClass
{
  public class InnerClass 
  {
  }
}

Why we need public inner whatever: struct, class, enum or static class?

I think that if it is inner then it must be only private or protected.

like image 355
Andriy Kizym Avatar asked Aug 11 '10 14:08

Andriy Kizym


2 Answers

You don't generally need public nested types - but they can be useful sometimes. They make it very clear that one type is explicitly associated with another.

They also allow the nested type to access the private members of the enclosing type (in C#), which may be useful at times. I would guess that List<T>.Enumerator may do that, for example. In Java the access rules work the other way round - the enclosing class has access to the private members of the nested classes.

I think would have to explain why you'd want to explicitly prohibit this rather than why it's needed, as such. I can't think of anywhere else that you can specify an access modifier but can't make it public, other than for inconsistency (declaring a public method with an internal return type, for example).

like image 141
Jon Skeet Avatar answered Oct 01 '22 10:10

Jon Skeet


Public inner types are generally not recommended, see this reference http://msdn.microsoft.com/en-us/library/tdz1bea9(v=VS.71).aspx

...but since there are (may be) exceptions, this is still allowed

like image 22
Mahol25 Avatar answered Oct 01 '22 11:10

Mahol25