Inheritance is a fundamental principle of object-oriented programming. It allows a class to inherit the behavior or characteristics from base class to child class.
Inheritsstatement is used to declare a new class, called a derived class, based on an existing class, known as a base class.
Here are some of the inheritance rules, and the modifiers you can use to change the way classes inherit or are inherited:
Publicclass cannot inherit a
Privateclass, and a
Friendclass cannot inherit a
Visual Basic introduces the following class-level statements and modifiers to support inheritance.
Inheritsstatement: Specifies the base class.
NotInheritablemodifier: Prevents programmers from using the class as a base class.
MustInheritmodifier: Specifies that the class is intended for use as a base class only. Instances of
MustInheritclasses cannot be created directly; they can only be created as base class instances of a derived class.
Let's take a look at an example of class inheritance. The following is the base class
Animal which contains a single
Name property and a method
PrintName which will print the name of the animal on the Console window.
Class Animal Public Property Name As String Public Sub New(ByVal name As String) name = name End Sub Public Sub PrintName() Console.WriteLine(Name) End Sub End Class
Here are the two-child classes
Dog, both classes have their method called
Class Cat Inherits Animal Public Sub New(ByVal name As String) MyBase.New(name) End Sub Public Sub Meow() Console.WriteLine("Meow!") End Sub End Class Class Dog Inherits Animal Public Sub New(ByVal name As String) MyBase.New(name) End Sub Public Sub Bark() Console.WriteLine("Bark!") End Sub End Class
In the above example, we used the
MyBase keyword in the constructor of the
MyBase.New, we can call the constructor of the base class.
The following code shows how to use the child class object and call the parent class method.
Dim cat As Cat = New Cat("Stanley") Dim dog As Dog = New Dog("Jackie") cat.PrintName() cat.Meow() dog.PrintName() dog.Bark()
You can see that both child class objects
dog can access the
PrintName() method of the parent class as well as their methods