Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

Defining Classes

As mentioned previously, classes are the fundamental programmatic structure you'll use when constructing VB.NET applications. One or more classes are contained in a single source code file and declared using the Class keyword. Building on the example from Figure 4.1, the Offerings class would be declared as follows:

Public Class Offerings
  ' Members to handle course offerings information
End Class

Note that VB.NET expands the modifiers you can prefix to the name of the class beyond Public and Private (the default) and includes Protected, Friend, and Protected Friend. A protected class is one that is nested inside another class and specifies that only derived classes can see it. For example, assume that the Offerings class contains a nested Course class defined as follows:

Public Class Offerings
    Protected Class Course
    Public Function ListCourses() As DataSet
          ' Query code to get the courses
        End Function
    End Class
End Class

By using the keyword Protected, a client cannot directly instantiate an object of type Offerings.Course to call its ListCourses method. The client can instead get access to the Course object only through methods of the Offerings class itself. In this way, protected access is no different from private access and is analogous to the "Public Not Createable" setting in VB 6.0. However, protected access also allows any classes that inherit from Offerings to have full access to the Course class as follows:

Public Class NewOfferings
  Inherits Offerings

   Public Sub ShowCourse()
     Dim objCourse As New Course()
      Dim objDs As DataSet
      objDS = objCourse.ListCourses()
      ' Other code to manipulate the courses
   End Sub
End Class

Although the Protected keyword affects the visibility of nested classes in derived classes, as in VB 6.0, the Friend keyword restricts the visibility of a class to code within the project in which it is defined. In the previous example, if the Offerings class had been defined with only the Friend keyword, it would still have been visible to all calling code within the project but could not have been instantiated by any code outside the project. In addition, any derived classes such as NewOfferings also would have to also be marked as Friend because not doing so would expand the access to the base class. Finally, a nested class can be marked as Protected Friend so that it is visible both in derived classes and code within the same project.

  • + Share This
  • 🔖 Save To Your Account