Interfaces and Inheritance – Visual Basic.NET Tutorials

Many classes have members in common. For example, all classes implement the ToString method. Different Stream classes implement the Read and Write methods.

To provide the consistency between classes, you could create a Person base class with common members shared between the classes, and derive Student, Faculty, and Staff classes from Person.

In addition to providing consistency, this inheritance would allow you to pass an instance of any of the classes to a method that accepted an instance of the Person base class. This concept is called polymorphism.

You can derive new classes from almost any .NET Framework class. One of the most useful classes to derive from is System.ApplicationException. By deriving a new application type, you can provide application-specific information.

The following code sample demonstrates overriding the Message property, but you can override other members or add new members.

Class DerivedException

     Inherits System.ApplicationException

      Public Overrides ReadOnly Property Message() As String

         Get

             Return "This is my custom error message."

         End Get

     End Property 

End Class

In this video (with the transcript below), I explain inheritance a bit more:

Consider needing to create classes for different animals, such as eagles, penguines, dogs, and bears. Each of these animals has many characteristics in common, as well as unique characteristics.

You should create a hierarchy of classes, starting with a common class that defines characteristics common to all animals. As shown in the picture, this might include members for the Brain, Lungs, Muscle, and Heart.

From that base class, you could derive a Vertibrate class that would include all the members of the Animal class, but adds a member for the Spine.

While you could derive your Eagle, Penguin, Dog, and Bear classes from the base Vertibrate class, you can benefit by adding another level of hierarchy to add common members required by the Dog and Bear (both mammals) and the Eagle and Penguin (both birds). Therefore, the example shows Mammal and Bird classes.

From those classes, you could then derive your final classes. While this much hierarchy wouldn’t required for four classes, if you later had to add classes for other animals, such as insects, you would have much less work to do, because you could inherit the common traits in the base classes. Additionally, you could write methods that would accept an instance of the Animal class, and pass any class derived from Animal as a parameter.

Interfaces

Interfaces define a set of members (such as properties and methods) that classes deriving from the interface can inherit or override. This helps to provide consistency between classes, which makes development easier.

Often, custom classes are based on interfaces. Interfaces provide a default set of properties and methods that saves you from needed to create them from scratch. Often, they also define a set of properties and methods that custom classes must conform to.

Interfaces are also helpful when developing classes in a hierarchical structure. For example, if you are creating an application for use at a university, you might need to create classes to represent students, faculty, and staff. Each of these classes would have several things in common, such as the person’s name and phone number. Each class would also have unique members. For example, the Student class might have an EnrolledClasses member that would not be necessary for the other classes.

How to Implement IComparable

By default, a custom class you create can’t be sorted. To enable sorting, the class needs to implement the IComparable interface. IComparable includes the CompareTo method, which returns a value that indicates how any two values compare.

Consider the ShoppingCartItem class shown below. If you added a many instances of ShoppingCartItem to an array, you might want to sort them using the price property. The price property is a double, which already implements IComparable (and thus the CompareTo method). To make ShoppingCartItem sortable by price, implement the IComparable interface, override the IComparable.CompareTo method, and then call the price.CompareTo method.

Public Class ShoppingCartItem

    Implements IComparable

    Public itemName As String

    Public price As Double

    Public Sub New(ByVal _itemName As String, ByVal _price As Double)                

        Me.itemName = _itemName

        Me.price = _price

    End Sub

    Public Function CompareTo(ByVal obj As Object) As Integer

        Dim otherItem As ShoppingCartItem = DirectCast(obj, ShoppingCartItem)

        ReturnMe.price.CompareTo(otherItem.price)        

    End Function

End Class

This video shows you how to implement interfaces easily using Visual Studio:

Common Interfaces

This table lists the most commonly used interfaces in the .NET Framework. You can also create your own interfaces, and derive new classes from existing classes that are not interfaces.

Interface

Used for

IComparable Values that can be sorted in a collection, such as numeric and string classes.
IDisposable Large objects that consume considerable resources. This interface defines methods for disposing of an object manually.
IConvertible Classes that can be converted to a base type such as Boolean, Byte, Double, or String.
ICloneable Classes that can be copied
IEquatable Classes that can be compared for equality
IFormattable Classes that can be converted into a specially formatted string. This interface provides greater flexibility than the standard ToString method offered by the base Object class.

Return to the .NET Framework Fundamentals Table of Contents.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>