The MyBase and MyClass keywords let you access the members of the base class and the derived class explicitly. To see why they’re useful, edit the ParentClass, as shown here:
Override Method4 in the derived class, as shown here:
Switch to the test form, add a button, declare a variable of the derived class, and call its Method4:
Dim objDerived As New DerivedClass() Debug.WriteLine(objDerived.Method4)Code language: CSS (css)
What will you see if you execute these statements? Obviously, the string Derived Method4. So far, all looks reasonable, and the class behaves intuitively. But what if we add the following method in the derived class?
Public Function newMethod() As String Return (Method1()) End FunctionCode language: PHP (php)
This method calls Method1 in the ParentClass class because Method1 is not overridden in the derived class. Method1 in the base class calls Method4. But which Method4 gets invoked? Surprised? It’s the derived Method4! To fix this behavior (assuming you want to call the Method4 of the base class), change the implementation of Method1 to the following:
Public Overridable Function Method1() As String Return (MyClass.Method4()) End FunctionCode language: PHP (php)
If you run the application again, the statement
Console.WriteLine(objDerived.newMethod)Code language: CSS (css)
will print this string:
I'm the original Method4
Is it reasonable for a method of the base class to call the overridden method? It is reasonable because the overridden class is newer than the base class, and the compiler tries to use the newest members. If you had other classes inheriting from the DerivedClass class, their members would take precedence.
Use the MyClass keyword to make sure that you’re calling a member in the same class, and not an overriding member in an inheriting class. Likewise, you can use the keyword MyBase to call the implementation of a member in the base class, rather than the equivalent member in a derived class. MyClass is similar to MyBase, but it treats the members of the parent class as if they were declared with the NotOverridable keyword.