Lesson 3: Interface Polymorphism

Lesson 3: Interface Polymorphism

Interfaces allow you to define contracts for behavior. Different and diverse classes can implement the same interfaces and can thus interact with other objects in a polymorphic manner. In this lesson, you will learn how to define an interface, how to implement an interface, and how objects can interact through an interface.

After this lesson, you will be able to

  • Describe how to define an interface

  • Describe how to implement an interface

  • Explain how interfaces enable polymorphism

Estimated lesson time: 30 minutes

An interface is a contract. Any object that implements a given interface guarantees to provide an implementation of the members defined in that interface. If an object requires interaction with a specific interface, any object that implements that interface can supply the requisite interaction.

An interface defines only the members that will be made available by an implementing object. The definition of the interface states nothing about the implementation of the members, only the parameters they take and the types of values they will return. Implementation of an interface is left entirely to the implementing class.

It is possible, therefore, for different objects to provide dramatically different implementations of the same members. Take, for example, an interface named IShape, which defines a single method CalculateArea. A Circle class implementing this interface will calculate its area differently than a Square class implementing the same interface. However, an object that needs to interact with an IShape can call the CalculateArea method in either a Circle or a Square and obtain a valid result.

Defining Interfaces

Interfaces are defined with the Interface (interface) keyword. For example:

Visual Basic .NET

Public Interface IDrivable End Interface

Visual C#

public interface IDrivable { }

This declaration defines the IDrivable interface, but does not define any members. Member methods must be defined with the method signature, but without access modifiers such as public, private, and so on. The interface access modifier determines the access modifier of the interface members. Thus, if you have a Public interface, all members must be Public as well. The following example demonstrates how to add methods to an interface:

Visual Basic .NET

Public Interface IDrivable Sub GoForward(ByVal Speed As Integer) Sub Halt() Function DistanceTraveled() As Integer End Interface

Visual C#

public interface IDrivable { void GoForward(int Speed); void Halt(); int DistanceTraveled(); }

You also can add properties to your interface definitions. A definition for a property must include ReadOnly or WriteOnly when appropriate (in Visual Basic) or define getters, setters, or both (in Visual C#), as well as specify the return type for the property. An example of a property definition follows:

Visual Basic .NET

Public Interface IDrivable ' Additional member definitions omitted ' This defines a read-only property. ReadOnly Property FuelLevel() As Integer End Interface

Visual C#

public interface IDrivable { // Additional member definitions omitted int FuelLevel { get; // To define a read-write property, add a set statement here } }

Although you can define properties in interfaces, you are not allowed to define fields. This restriction ensures that classes that interact through the interface do not have access to the internal data of an object.

Interfaces can also define events. Interface events represent events raised by objects implementing the interface. Although any class that implements an interface must provide an implementation for any member events, objects that interact through that interface are not obliged to handle any raised events. A default delegate type is provided for the event in Visual Basic .NET; in Visual C#, you must explicitly designate the delegate type for the event. The following example demonstrates an interface definition for a member event:

Visual Basic .NET

Public Interface IDrivable ' Additional member definitions omitted Event OutOfFuel(ByVal sender As Object, e As System.EventArgs) End Interface

Visual C#

public interface IDrivable { // Additional member definitions omitted event System.EventHandler OutOfFuel; }

To define an interface

Declare the interface using the Interface keyword (Visual Basic) or the interface keyword (Visual C#). Within the interface definition, define the signatures for the member methods, properties, and events that the interface will expose.

Polymorphism with Interfaces

Any object that implements a particular interface can interact with any other object that requires that interface. Take the following method, for example:

Visual Basic .NET

Public Sub GoSomewhere(ByVal V As IDrivable) ' Implementation omitted End Sub

Visual C#

public void GoSomewhere(IDrivable v) { // Implementation omitted }

This method requires an implementation of the IDrivable interface. Any object that implements this interface can be passed as a parameter to this method. The object will be implicitly cast to the appropriate interface. When an object is interacting through its interface, only the interface members are accessible.

You also can explicitly cast objects that implement specific interfaces. The following example demonstrates how to cast a Truck object as the IDrivable interface (note that for this to work, Truck must implement IDrivable):

Visual Basic .NET

Dim myTruck As New Truck() Dim myVehicle As IDrivable ' Casts myTruck to the IDrivable interface myVehicle = CType(myTruck, IDrivable)

Visual C#

Truck myTruck = new Truck(); IDrivable myVehicle; // Casts myTruck to the IDrivable interface myVehicle = (IDrivable)myTruck;

Implementing Interfaces

In Visual Basic, interfaces are implemented by classes or structures with the Implements keyword. In Visual C#, the colon (:) is used to designate that a class or struct implements a specific interface. The following example demonstrates how to indicate that a class implements a specific interface:

Visual Basic .NET

Public Class Truck Implements IDrivable ' Additional implementation code omitted End Class

Visual C#

public class Truck : IDrivable { // Additional implementation code omitted }

Classes can implement multiple interfaces. If you want to declare a class to implement multiple interfaces, you can specify the interfaces to be implemented as a comma-separated list as shown in the following examples.

Visual Basic .NET

Public Class Truck Implements IDrivable, IFuelBurning, ICargoCarrying ' Additional implementation code omitted End Class

Visual C#

public class Truck : IDrivable, IFuelBurning, ICargoCarrying { // Additional implementation code omitted }

When a class or structure implements an interface, you must provide a separate implementation for each member of that interface. If multiple interfaces are implemented, you must provide an implementation for every member of each interface.

Implementing Interface Members in Visual C#

In Visual C#, you implement interface members in your class or structure by providing a member that has the same name as the member defined in the interface. This member must have the same access level as the interface. The following example demonstrates how to implement an interface member method:

Visual C#

public interface IDrivable { void GoForward(int Speed); } public class Truck : IDrivable { public void GoForward(int Speed) { // Implementation omitted } }

When members of an interface are implemented in this manner, they are available to both the interface and the class itself. Thus, they can be accessed whether the object is cast as its own class or as the interface that it implements.

It is also possible to explicitly implement the interface and make its members unavailable to the interface of the class that is implementing it. When a member is implemented in this manner, the member can be accessed only when the object is cast as the interface it implements. You explicitly implement an interface member by providing an implementation for the fully qualified interface name. The following example demonstrates how to explicitly implement the GoForward method of IDrivable:

Visual C#

public class Truck : IDrivable { void IDrivable.GoForward(int Speed) { // Implementation omitted } }

Note that this member has no access modifier. Because it is an explicit implementation of the interface member, it will have the same access level as the member defined by the interface.

To implement an interface with Visual C#

  1. Define a class that implements the desired interface. Use the colon (:) to declare which interface is being implemented in the class declaration. A class can implement multiple interfaces.

  2. Provide an implementation for each member of the interface:

    • If you want a member to be available to the class and the interface, create a member with the same name, access level, and signature as the member defined by the interface.

    • If you want a member to be available only to the interface, implement it using the fully qualified interface name. It is unnecessary to provide an access modifier.

Implementing Interface Members with Visual Basic .NET

In Visual Basic .NET, you specify that a class member implements an interface member by using the Implements keyword. The class member that implements the interface member must have the same signature as defined in the interface, but it does not need to have the same access level. The following example shows how to implement an interface member method:

Visual Basic .NET

Public Interface IDrivable Sub GoForward(ByVal Speed As Integer) End Interface Public Class Truck Implements IDrivable Public Sub GoForward(ByVal Speed As Integer) Implements IDrivable.GoForward ' Implementation omitted End Sub End Class

The class member that implements an interface member need not have same name as the interface member. For example, the following is a perfectly legal implementation of the GoForward method of the IDrivable interface:

Visual Basic .NET

Public Sub Move(ByVal Speed As Integer) Implements IDrivable.GoForward ' Implementation omitted End Sub

Any calls to the GoForward method of the interface in the foregoing example will be mapped to the Move method of the implementing class.

You also can specify a different access level for a class method that implements an interface method. For example, you can implement a method of a Public interface with a Private class method. If you take this approach, the method will be Public when accessed through the interface, but will remain Private when accessed as a member of the class.

To implement an interface with Visual Basic .NET

  1. Define a class that implements the desired interface. Use the Implements keyword to declare which interface is being implemented in the class declaration. A class can implement multiple interfaces.

  2. Use the Implements keyword to provide an implementation for each interface member.

Lesson Summary

  • An interface defines a contract for behavior. It defines the members that will be exposed through the interface, and the parameters and return types of those members. Any object that implements an interface can interact with any object that requires that interface. Both classes and structures can implement interfaces, including multiple interfaces.

  • Implementation of interface members is left to the class or structure that implements the member.

  • The Implements keyword in Visual Basic .NET and the colon (:) in Visual C# declare that a class or structure implements an interface. If a class or structure implements an interface, it also must provide an implementation for each member defined in that interface.

  • In Visual C#, you can implement interface members in two ways:

    • By implementing a member with the same name, signature, and access level as the member defined in the interface. This member will be available to both the class that implements it and the interface.

    • By explicitly implementing the interface member using the fully qualified member name. If implemented in this manner, the member will be available only to the interface.

  • In Visual Basic .NET, you implement an interface member by creating a class or structure member with the same signature as the interface member, and use the Implements keyword to map the interface member to the class member. The name and access level of the class member can differ from that of the interface member.



MCAD(s)MCSD Self-Paced Training Kit(c) Developing Windows-Based Applications With Microsoft Visual Basic. Net a[.  .. ]0-316
MCAD(s)MCSD Self-Paced Training Kit(c) Developing Windows-Based Applications With Microsoft Visual Basic. Net a[. .. ]0-316
ISBN: 735619263
EAN: N/A
Year: 2003
Pages: 110

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net