Overridable and Overrides
Although Overridable and Overrides sounds quite technical, it isn't really because the meaning is just as you would use the words in normal English. That is, the one version will override or replace the settings of the original or earlier version. If something is Overridable, it can be replaced.
You are allowed to override a method in the parent class if that class has been made Overridable. Also it is important to remember that the signature of the overridden method must be the same as the signature of the parent method. ("Signature" was covered in an earlier article)
So if the parent class contains an Overridable method, then the child class may override that method. The developer of the child class has the choice as to whether to provide an overridden method or not. It is not mandatory.
The System.Object.ToString is designated as Overridable as we saw in the Object Browser :
You can create any String you like as the returned result of the ToString method. In the case of the Person Class, the Forename and Surname are possibly the two most useful pieces of core information. So I will use these as the returned value of the ToString function - that is, what the client code gets if it calls this method.
Here is that ToString method for the Person Class:
Public Overrides Function ToString() As String
Return m_forename & " " & m_surname
It finds the value of the m_forename and m_surname for the current instance and returns those values as a concatenated string, with a space between the two parts.
Concatenated is simply developer-speak for "joined together".
Testing out this method, place the following code in the Button click event of Form1 in the ClassBasics project:
' Create a new Person Instance
Dim RealPerson As New Person("Ged", "Mead")
'  Display using the default ToString method
Label1.Text = RealPerson.ToString
This time, you will get the result you want:
In this article I covered one method, ToString, in some depth. You saw that all classes inherit from System.Object and that we can override the ToString method in the System.Object class. We can do this because the declaration of the System Object's ToString method includes the Overridable modifier.
If you choose to override a method there are two key requirements:
- You must include the Overrides modifier in the child method declaration
- The signature must be the same as that of the parent method.
You can get a lot of very useful information about classes and hierarchies by using the Object Browser tool in Visual Studio.
Of course, you can include many other methods in a class - and probably would. We will look at some other methods in a later article.
In the next article in this series, I will look at Properties in more detail, how to validate values and send messages back to client code.