Information Technology Reference
In-Depth Information
Example of Different Classes Implementing an Interface
The following code illustrates several aspects of interfaces that have been covered. The pro-
gram declares a class called Animal , which is used as a base class for several other classes that
represent various types of animals. It also declares an interface named ILiveBirth .
Classes Cat , Dog , and Bird all derive from base class Animal . Cat and Dog both implement
the ILiveBirth interface, but class Bird does not.
In Main , the program creates an array of Animal objects and populates it with a class object
of each of the three types of animal classes. Finally, the program iterates through the array, and
using the as operator, retrieves references to the ILiveBirth interface of each object that has
one, and calls its BabyCalled method.
interface ILiveBirth // Declare interface
{
string BabyCalled();
}
class Animal { } // Base class Animal
class Cat : Animal, ILiveBirth // Declare class Cat
{
string ILiveBirth.BabyCalled()
{ return "kitten"; }
}
class Dog : Animal, ILiveBirth // Declare class Dog
{
string ILiveBirth.BabyCalled()
{ return "puppy"; }
}
class Bird : Animal // Declare class Bird
{
}
Search WWH ::




Custom Search