There are a didderence between abstract classes and interfaces, the abstrac classes are used to derive new objects, like humanoid that we could use to derive Persons, Monkey chid types
public class Humaoid
{
public Humanoid(){}
public void StandOnTwoFeet(){}
public void Walk()
{
//TO DO some code implementations here
}
}
public class Persons : Humaoid
{
public override Humanoid(){}
public override void StandOnTwoFeet(){}
public override void Walk()
{
//TO DO some code implementations here
}
}
Abstract classes are used to employ polymorphism only between types who belong to the same family
Abstract classes familly members(methods, properties, fields, events) can use accessors like public private, protected
Abstract classes could have some of their method implemented with code
Now move to the interfaces
Persons and girafes are both mamifers but they don't belong to the same type as the persons belong to the Humonoids and the girafes belong to the Antilops
public Interface IMamifer
{
bool IsMamifer();
}
public Person: Humonoid, IMamifer
{
public override Humanoid(){}
public override void StandOnTwoFeet(){}
public override void Walk()
{
//TO DO some code implementations here
}
// The interface method
public bool IsMamifer()
{return true;}
}
public Girafe: Antilops, IMamifer
{
public override Humanoid(){}
public override void StandOnTwoFeet(){}
public override void Walk()
{
//TO DO some code implementations here
}
// The interface method
public bool IsMamifer()
{return true;}
}
Interfaces' members coudn't be implemented with code within the Interface scope, they coudn't use accessors like public private..... and they could tie between different types those have something in common
Now, you tell me give me a real use case where exactly the interfaces are useful as the abstract classes are used to derive new types so what about the interfaces???
Ok
Imagine that you want to select all earth mamifers from the other existed types and put them in a given list, recall that mamifers are dispatched in more than one type
foreach(IMamifer creature in Earth.Creature)
{
List.Items.Add(creature);
}
instead of
foreach(Person creature in Earth.Creature)
{
List.Items.Add(creature);
}
foreach(Girafe creature in Earth.Creature)
{
List.Items.Add(creature);
}
.
.
.
And the list is so long all those could be replaced by the first loop