- Advanced
- Conversions
- The .NET Framework Type Hierarchy
- Overriding
- Abstract Classes and Methods
- Conclusion
Abstract Classes and Methods
In the examples we've been using so far in this chapter, Person, Employee, and Customer have all been classes that can be created using the New operator. However, there may be situations where a base class should never be createdperhaps there should only be instances of the Employee type and Customer type and never an instance of the Person type. It's possible just to add a comment saying Person should never be created, or Person might have a Private constructor to make it impossible to create. However, Person can also be designated as an abstract type. An abstract type is the same as a regular (or concrete) type in all respects except for one: An abstract type can never directly be created. In the following example, Person is now declared as an abstract type, using the MustInherit modifier.
MustInherit Class Person Public Name As String Public Address As String Public City As String Public State As String Public ZIP As String Sub Print() Console.WriteLine(Name) Console.WriteLine(Address) Console.WriteLine(City & ", " & State & " " & ZIP) End Sub End Class Class Customer Inherits Person Public CustomerID As Integer End Class Class Employee Inherits Person Public Salary As Integer End Class
Just because a class is abstract and cannot be created, it does not mean that it cannot have constructors. An abstract class may have constructors to initialize methods or pass values along to base class constructors.
Abstract classes are special in that they can also define abstract methods. Abstract methods are overridable methods that are declared with the MustOverride keyword and provide no implementation. A class that inherits from a class with abstract methods must provide an implementation for the abstract methods or must be abstract itself. For example, the Person class could define an abstract PrintName method that each derived class has to implement to display the person's name correctly.
MustInherit Class Person Public Name As String Public Address As String Public City As String Public State As String Public ZIP As String MustOverride Sub PrintName() Sub Print() PrintName() Console.WriteLine(Address) Console.WriteLine(City & ", " & State & " " & ZIP) End Sub End Class Class Customer Inherits Person Overrides Sub PrintName() Console.Write("Customer ") Console.WriteLine(Name) End Sub Public CustomerID As Integer End Class Class Employee Inherits Person Overrides Sub PrintName() Console.Write("Employee ") Console.WriteLine(Name) End Sub Public Salary As Integer End Class
In this example, Person.Print can call the PrintName method, even though Person supplies no implementation for the method, because it is guaranteed that any derived class that can be instanced must provide an implementation.