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.
Inherits
statement 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:
NotInheritable
keyword.Public
class cannot inherit a Friend
or a Private
class, and a Friend
class cannot inherit a Private
class.Visual Basic introduces the following class-level statements and modifiers to support inheritance.
Inherits
statement: Specifies the base class.NotInheritable
modifier: Prevents programmers from using the class as a base class.MustInherit
modifier: Specifies that the class is intended for use as a base class only. Instances of MustInherit
classes 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 Cat
and Dog
, both classes have their method called Meow()
and Bark()
respectively.
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 Cat
and Dog
classes.
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 cat
and dog
can access the PrintName()
method of the parent class as well as their methods Meow()
and Bark()
respectively.