WEBINAR:
On-Demand
Application Security Testing: An Integral Part of DevOps
I Want My Inheritance
Looking at the Water and Fish classes, it is easy to see some class commonalities. Inheritance involves extracting that commonality into a separately defined class. That new class is called a
superclass, parent class or
base class. The original classes then inherit from the new base class and become
child classes, which are also referred to as
derived classes or
subclasses.
In this example, you can define a new base class named OceanElement that defines any element that can be placed into the WA-TOR ocean. Both the
location and
image properties from the child classes are extracted from those classes and instead implemented in the OceanElement class:
Public MustInherit Class OceanElement
Protected myLocation As Point
Public Property Location() As Point
Get
Return myLocation
End Get
Set(ByVal Value As Point)
myLocation = Value
End Set
End Property
Public MustOverride ReadOnly Property Image() _
As Image
End Class
Notice the
MustInherit keyword on the Class declaration. This keyword identifies the class as an
abstract class. An abstract class is one that defines properties and methods but cannot itself be instantiated. This keyword is frequently used in base classes when the base class defines common functionality but does not itself represent an object in the application.
The
Protected keyword in the declaration for the location ensures that the location value can only be accessed through the inheritance hierarchy. This means that only classes that inherit from this class or inherit from classes that inherit from this class can access that value directly. All other classes must access the value through the defined
Property statements.
The
MustOverride keyword in the declaration for the
Image property denotes that the child classes must override this property. This keyword is needed in this case because each child class defines its own Image object containing its visual representation for the simulation.
The Water, Fish, and Shark classes all then inherit from this OceanElement base class. The Water class is shown as an example:
Public Class Water : Inherits OceanElement
Private Shared myImage As Image _
= Image.FromFile("../water.jpg")
Public Overrides ReadOnly Property image() _
As Image
Get
Return myImage
End Get
End Property
Public Sub New(ByVal location As Point)
myLocation = location
End Sub
End Class
Notice how much less code is here than in the earlier example of the Water class. The
Image Property statement overrides the
Image property implemented in the base class to define the unique image for the Water class. The constructor for the Water class sets the
myLocation variable, which is now maintained by the base class. The Water class has access to this variable from the base class because it was defined in the base class with
Protected scope.