JavaScript Editor JavaScript Editor     JavaScript Debugger

Previous Section Next Section

Main Page

Class vs. Object Members

There's another important distinction to understand when dealing with members in OOP: class members vs. object members. Members that apply to a class and are invoked with the class name are called shared or static or class members; the members that apply to objects created from the class are called instance or object members. For example, if TextBox1 is an object, then its Text property is an instance or object member, because you use it with the object's name: TextBox1.Text = "Hello from Visual Basic".

On the other hand, you can make members shared or class members, which you use with the class name, if you use the Shared keyword. Using this keyword makes a member into a class member, which you can use with just the class name—no object needed. (It also makes all objects share that member, as we'll see in this chapter.) Here's an example; in this case, I'll add a class method named Add to a class named Mathematics—this method just takes two integers and adds them, returning their sum:

    Public Class Mathematics
        Shared Function Add(ByVal x As Integer, ByVal y As Integer) _
            As Integer
            Return x + y
        End Function
    End Class

Now I can use this new class method using the name of the class, Mathematics, without needing an object of that class:

    Private Sub Button1_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button1.Click
        TextBox3.Text = Mathematics.Add(TextBox1.Text, TextBox2.Text)
    End Sub

As we'll see in this chapter, using the keyword Shared also means that the shared method or data member is shared across all instances of its class. For example, if a class has a shared data member named Count, then every object of that class uses the same exact memory location for Count.

Previous Section Next Section

JavaScript Editor Free JavaScript Editor     JavaScript Editor