VB.NET 1.1 Tutorial - InheritanceInheritance represents the relationship between two objects A and B, such that B 'is a kind of' A. In UML, we show this by using the triangle symbol, as shown below. ![]() We can use some ordinary everyday objects to expand on this concept. Let us say that we have a 'person' object and a 'dog' object. So how are they related? A 'dog' is an animal, more specifically a 'dog' is a mammal. A 'person' is also a mammal, so we have found a common parent for the two objects. As we have seen in previous pages, the 'person' and 'dog' objects share an amount of common information and subsequently common behaviour. It is this common data that they both get from the parent object, so we could create an object that has the common data within it. In the following diagram, I have tried to show one possible hierarchial structure that will allow the 'person' object and the 'dog' object to share common data logically. ![]() The diagram shows a flaw in our thinking, 'dogs' can be domestic or wild. A 'wild' dog will not have a name or address, so we need to clarify each type of 'dog' object with a unique identity. So we may have our 'dog' object representing domestic dogs, while we change the object name to 'WildDog' for the other object of type 'dog'. Finally I have shown that we can inherit from our dog objects into individual breeds of dog if we wished to. In general when talking about inheritance, we talk about a type of object. An object inherits from a parent, known as its super-type. A child is inherited from an object and is known as a sub-type. Implementing InheritanceWhen we create a Windows Form application, the form for our application uses inheritance. So that we do not have to create all of the code ourselves, the form inherits all of the common data needed to draw a form from the System.Windows.Forms.Form class using the Inherits keyword. Public Class HelloFrm Inherits System.Windows.Forms.Form Similarly, from the example above, we can inherit an object of type Terrier from an object of type Dog. Public Class Terrier Inherits Dog This code declares a new class, Terrier, that inherits from Dog. The derived class inherits all the Public and Protected members of the base class, both member variables and methods. The derived class is free to implement its own version of a base class method. It does so by marking the new method with the keyword Overrides. This indicates that the derived class has intentionally hidden and replaced the base class method. However, this will only work if the base class method is marked as an overridable method. Public Overrides Function setSpecies( ByVal Species As String ) ' Ignore parameter Me.species = "Terrier" End Function What Next?Return to the Tutorial Contents. |