Classes and structs can inherit from interfaces in a manner similar to how classes can inherit a base class or struct, but a class or struct can inherit more than one interface and it inherits only the method names and signatures, because the interface itself contains no implementations.
class MyClass: IMyInterface
{
public object Clone()
{
return null;
}
// IMyInterface implemented here...
}
Uses of Interfaces
- Interface-Based Polymorphism (Substitutability) - Substitutability allows a descendant class to be used anywhere an associated parent class is used. In object oriented programming a variable could refer to one object at one time and then another object another time. This allows the designer of software to create both a dog.run and a cat.run methods and then decide at runtime whether the variable will be a dog or a cat. Interfaces are a common coding element used to implement this type of polymorphism.
- Interfaces allow for horizontal class design. In a class tree, inheritance is used to design classes vertically with "is-a" relationships. You add functionality from top to bottom adding methods and properties to decsendant classes. Interfaces allow you to design horizontally across your class tree using a "behaves-as" or "looks-like" relationship insisting certain classes implement a common interface.
Visual C# 2008 Working WinForms Example
The following example demonstrates implementing a very simple interface. The interface is named IHuman which includes one property and one method. Our resulting class is named CyborgHuman and, for clarity, our CyborgHuman class also inherits from a class called Cyborg.
Create a form and place a button on it and alter the code as follows:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CR_Interfaces
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
CyborgHuman MyRobot = new CyborgHuman();
MyRobot.HumanName = "Nicole";
MyRobot.Speak("Hi, my name is " + MyRobot.HumanName + ".");
}
}
public interface IHuman
{
//Interface property.
string HumanName {get; set;}
//Interface method.
void Speak(string pMessage);
}
//Sample class for demonstration.
public class Cyborg
{
}
public class CyborgHuman: Cyborg, IHuman
{
public string HumanName {get; set;}
public void Speak(string pMessage)
{
MessageBox.Show(pMessage);
}
}
}
Default Interface Visibility: Internal
If you do not specify an interfaces visibility, the default is Internal (accessible from types in the same assembly) but an interface's members are always public -- which makes sense but is noteworthy.
interface ITalk {..} //Default visibility is Internal.