How to: Define a Class That Uses Members of an Existing ClassÂ
You can use members of an existing class in another class that derives from it.
In the following example, suppose you want to define a special kind of Button that acts like a normal Button but also exposes a method that reverses the foreground and background colors.
To define a class that uses the members of an already existing class
Use a Class Statement (Visual Basic) to define a class from which to create the object you need.
Public Class reversibleButton
Be sure an End Class statement follows the last line of code in your class. By default, the integrated development environment (IDE) automatically generates an End Class when you enter a Class statement.
Follow the Class statement immediately with an Inherits Statement. Specify the class from which your new class derives.
Inherits System.Windows.Forms.Button
Your new class inherits all the members defined by the base class.
Add the code for the additional members your derived class exposes. For example, you might add a
reverseColors
method, and your derived class might look as follows:Public Class reversibleButton Inherits System.Windows.Forms.Button Public Sub reverseColors() Dim saveColor As System.Drawing.Color = Me.BackColor Me.BackColor = Me.ForeColor Me.ForeColor = saveColor End Sub End Class
If you create an object from the
reversibleButton
class, it can access all the members of the Button class, as well as thereverseColors
method and any other new members you define onreversibleButton
.
Compiling the Code
Be sure the compiler can access the class from which you intend to derive your new class. This might mean fully qualifying its name, as in the preceding example, or identifying its namespace in an Imports Statement. If the class is in a different project, you might need to add a reference to that project. For more information, see Referencing Namespaces and Components.
See Also
Tasks
How to: Create an Object
How to: Reuse a Working Component
How to: Access Shared and Nonshared Members of an Object
How to: Create Derived Classes