C# FAQ: What is the difference between nested classes in CSharp and Java
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
| CSharp-Online.NET:FAQs |
| edit |
What is the difference between nested classes in C# and Java?
Class declarations in both the C# and Java languages can be nested inside one other. But, there are differences in the implementations.
The Java language defines two types of nested classes—nested class (inner class) and static nested class. An inner class has a one-to-one relation to its enclosing class, i.e., each enclosing class instance contains a corresponding inner class instance which contains no static methods and which can access the instance variables of the enclosing class. In comparison, a static nested class has access to the static members and methods of the enclosing class.
public class Computer // Java example { private CPU cpu; private static class CPU { String serialNumber; } }
C# supports an analogue of Java static nested classes; but, C# has nothing similar to Java inner classes. The following C# declarations are the equivalent of the preceding Java declarations:
public class Computer // C# example { private CPU cpu; private class CPU { string serialNumber; } }
Whereas a Java nested class can be declared in any code block including methods, C# does not offer this flexibility. Powerful design patterns can be created by developers who use this Java capability with anonymous inner classes.