Views: 11.8K
Replies: 2
Archived
|
Private Interface InheritanceI had a chance to see the following private interface inheritance code. Is this a common practice? Where is this being used? Thanks.
interface IAnimal { Eat() } class Dog : IAnimal { void IAnimal.Eat() {...} } Dog dog = new Dog() dog.Eat() // error IAnimal dog = new Dog() dog.Eat() // no error Jacob Jacob, Apr 11, 2011
|
|
Reply 1While implementing factory pattern...you need runtime polymorphism.
Two classes implementing same interface having different implementation, deciding object to initialize at runtime Interface iShape Sub DrawShape() End Interface Public Class Circle Implements iShape Public Sub DrawShape() Implements iShape.DrawShape Debug.WriteLine("this is drawing circle") End Sub End Class Public Class Square Implements iShape Public Sub DrawShape() Implements iShape.DrawShape Debug.WriteLine("this is drawing square") End Sub End Class Somewhere in your application, Sub main() Dim s As iShape s = New Circle s.DrawShape() s = New Square s.DrawShape() End Sub Hope this helps..... Saurin Saurin Travadi, Apr 21, 2011
|
|
Reply 2What you are doing in the Dog class is explicit interface implementation, when implementing an interface this way it can not be accessed through a class instance, only through an instance of the interface. Example:
var someDog = (IAnimal) dog; someDog.Eat(); // no error You would for instance use explicit interface implementation to support multiple interfaces, but I myself have never found a need to use it yet. Read more about explicit interface implementation on MSDN here (and also an example where it might be useful): http://msdn.microsoft.com/en-us/library/aa288461(v=vs.71).aspx This link might also be useful for further reading: http://stackoverflow.com/questions/143405/c-interfaces-implicit-and-explicit-implementation Hope that helps. Robert Blixt, Apr 12, 2011
|