Prev | Current Page 87 | Next

Guy Fouch?©, Trey Nash

"Accelerated VB 2008"


The MustInherit keyword tells the compiler that this class is meant to be used only as a
base class, and therefore it does not allow code to create instances of that class. Let??™s look at
an example:
Public MustInherit Class GeometricShape
Public Overridable Sub Draw()
End Sub
End Class
Public Class Circle
Inherits GeometricShape
Public Overrides Sub Draw()
'Do some drawing.
End Sub
End Class
Public Class EntryPoint
Shared Sub Main()
Dim Circle As New Circle
'This will not work!
'Dim shape2 As New GeometricShape
Circle.Draw()
End Sub
End Class
CHAPTER 3 n CLASSES AND STRUCTURES 42
It makes no sense to create a GeometricShape object all by itself because it??™s so abstract.
Typically, you??™d want to create a type of geometric shape, such as a circle, triangle, or square.
To enforce this, you mark the GeometricShape class as MustInherit. Therefore, if the code in
Main() attempts to create an instance of GeometricShape, a compiler error will be emitted.
Using the MustInherit keyword is a way of saying to the compiler that the deriving classes
must override the methods. Since the method must be overridden by the derived classes, it
makes no sense for the GeometricShape.Draw() member to have an implementation when you
can??™t ever create an instance of GeometricShape anyway.


Pages:
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
życzenia urodzinowe wierszyki szambo betonowe typy bukmacherskie Tango Olsztyn