Nested Classes

  • Thread starter Thread starter Bob Day
  • Start date Start date
B

Bob Day

Using VS2003, VB.NET, MSDE...

I am looking at a demo program that, to my surprise, has nested classes,
such as the example below. I guess it surprised me becuase you cannot have
nested subs, and I am not sure why you would want nested classes anyway.

Is there a URL that explains the advantages to nested classes, when they
would be used, etc? What are your thoughts?

Also, if a Class has nothing before it (i.e. no Public or Private, etc.), is
it automatically public or private?

Thanks!

Bob Day

Public Class x

Public Class y

Public Sub g()

End Sub

End Class

End Class
 
Nested classes and nested subs are two very different paradigms (at least in
terms of implementation). Most OOP languages allow for nested types
(classes). This allows classes to construct and use private helper classes,
which aids in enapsulation of private details that shouldn't be used/abused
elsewhere. Classes can also define private implimentations of public
interfaces this way - for example, creating a private enumerator that only
this collection class uses, where the private nested enumerator class
implements the public IEnumerator interface. The main collection class is
the only one who has true knowledge of this enumerator's details, and the
only one who can create an instance of it. The outside world only sees and
interacts with the public IEnumerator interface of the object.

-Rob Teixeira [MVP]
 
Bob,
In addition to Rob's comments.

Nested classes are useful for implementation details of the outer class (as
Rob suggested). For example if I were to define a LinkedList class I would
define a nested Node class that contained each link of the List.

' A single linked list.
Public Class LinkedList

Private Class Node
Public Data As Object
Public Next As Node

Public Sub New(data As Object, next As Node)
Me.Data = data
Me.Next = next
End Sub

End Class

Private m_head As Node

Public Sub Add(data As Object)
m_head = New Node(data, m_head)
End Sub

Public Readonly Property Head As Object
Get
If m_head Is Nothing Then
Return Nothing
End If
Return m_head.Data
End Get
End Property

End Class

Hope this helps
Jay
 
Back
Top