You might wonder if there is a possibility to override nonvirtual or nonoverridable (vb.net) methods. Suppose you are using a third party software then you may need to override some of its methods which are not declared as virtual, this is also a likely requirement when you are writing a wrapper to some existing controls/software/functionality.
This is actually not overriding the actual function but it is called hiding the base class implementation and this can be implemented as following
vb.net implementation:
Class myBaseClass
Public Function MyNonOverridableMethod() As String
Return "I am not overridable"
End Function
End Class
Class myDerivedClass
Inherits myBaseClass
Public Shadows Function MyNonOverridableMethod() As String
Return "I overrode my base class function"
End Function
End Class
Note that I have used keyword "shadows" here, which tells the runtime that these two functions are separate implementations (not correlated) in their respective classes.
now when I call them from Main
Sub Main()
Dim b As myBaseClass = New myDerivedClass()
Console.WriteLine(b.MyNonOverridableMethod())
Dim d As myDerivedClass = New myDerivedClass()
Console.WriteLine(d.MyNonOverridableMethod())
Console.ReadLine()
End Sub
This will print me
"I am not overridable"
"I overrode my base class function"
you can see, that this is still using runtime polymorphism, on runtime it sees that the function being called is not virtual so it has to be called from variable reference type (not the type of the object got created). Has the function being declared virtual, runtime will call it from the type of the object that has been created but not from the type of the reference pointer it is holding.(in case of base class function being declared virtual/nonoverridable and derived class overriding it, the previous example would always be printing "I overrode my base class function").
C# implementation for same:
public class myBaseClass
{
public string MyNonOverridableMethod()
{
return "I am not overridable";
}
}
public class myDerivedClass : myBaseClass
{
public new string MyNonOverridableMethod()
{
return "I overrode my base class function";
}
}
The only difference is that "Shadows" keyword is replaced by "New".
calling from Main will reproduce the same result.
public static void Main() |
| myBaseClass b = new myDerivedClass(); |
14 | Console.WriteLine(b.MyNonOverridableMethod()); |
16 | myDerivedClass d = new myDerivedClass(); |
17 | Console.WriteLine(d.MyNonOverridableMethod()); |