Home > Articles > Programming > Windows Programming

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


  1. Can I inherit from a form I created? How are properties dealt with?

  2. Absolutely, you can inherit from any class unless it is declared with the NotInheritable keyword (sealed in C#).

    Dealing with inherited properties is often a complex issue. For example, look at the following code:

    1: Imports System
    2: Imports System.Windows.Forms
    3: Imports System.Drawing
    5: Public Class ClassA : Inherits Form
    6: private lblMessage as New Label
    8: Public Sub New()
    9: lblMessage.Location = new Point(100,100)
    10: lblMessage.Height = 100
    11: lblMessage.Width = 200
    12: lblMessage.Text = "Hello World!"
    13: Me.Controls.Add(lblMessage)
    14: End Sub
    15: End Class
    17: Public Class ClassB : Inherits ClassA
    18: private lblMessage as New Label
    20: Public Sub New()
    21: lblMessage.Location = new Point(100,100)
    22: lblMessage.Height = 100
    23: lblMessage.Width = 200
    24: Me.Controls.Add(lblMessage)
    25: End Sub
    26: End Class
    28: Public Class StartForm
    29: Public Shared Sub Main()
    30: Application.Run(New ClassB)
    31: End Sub 
    32: End Class

    When you compile and run this application, the form defined by ClassB will display. Note that nowhere in this class do you set the Text property of the label declared on line 18. However, when you run the application, the label contains the text "Hello World!" This text is set in ClassA on line 12.

    This is not because the label from ClassB was inherited from ClassA, but rather because in ClassA's constructor, a label is created with the text in question, and added to the form. Recall that the first thing that occurs in any constructor is a call to its parent's constructor. Thus, by the time ClassB's constructor executes, there's already a label there with the words "Hello World!" You cannot, however, modify that label from ClassB because on line 6, it is declared as private, and therefore only accessible from ClassA. If you changed it to public, then you would receive an error because ClassB would have inherited the label lblMessage, and line 18 is trying to re-declare it—not a valid task.

    The bottom line is to be careful when inheriting from your own classes, and pay attention to the security context in which variables are declared.

  • + Share This
  • 🔖 Save To Your Account