Esse exemplo demonstra uma tentativa ... pegar mais do que tudo.
Interfaces são tipos também .. mas eles apenas expõem seu contrato. Então isso:
IPointy itPt = new IPointy();
.. não funciona. Considere isto:
interface IPointy {
void MyMethod();
}
class Pencil : IPointy {
void MyMethod() {
}
void MyOtherMethod() {
}
}
Você pode declarar um IPointy assim:
IPointy itPt = new Pencil();
.. no entanto, isso funcionará:
itPt.MyMethod();
.. isso não funcionará:
itPt.MyOtherMethod();
Isso ocorre porque MyMethod
faz parte do contrato IPointy .. MyOtherMethod
não é .. Espero que ajude.
EDIT: Expandindo isso para explicar meu comentário.
Herdar de uma classe representa um relacionamento "é-um". A implementação de uma interface representa um relacionamento "posso fazer".
Considere:
interface ISwitchable {
void SwitchOn();
void SwitchOff();
}
class Light : ISwitchable {
void SwitchOn() { }
void SwitchOff() { }
}
class Television : ISwitchable {
void SwitchOn() { }
void SwitchOff() { }
}
Tanto a televisão quanto a luz são herdadas da ISwitchable. A interface define um relacionamento "pode fazer". Ambos podem ser ativados ou desativados. Ambos os seguintes blocos de código são válidos:
ISwitchable mySwitchableObject1 = new Light();
ISwitchable mySwitchableObject2 = new Television();
mySwitchableObject1.SwitchOn(); // calls Light's SwitchOn method
mySwitchableObject2.SwitchOn(); // calls Television's SwitchOn method