Let's say i have two classes:
class Batman
{
public void Robin(){...}
public void Jump(){...}
}
class Superman
{
public void Kryptonie(){...}
public void Jump(){...}
}
Now, I have an instance of those classes:
public object Crossover()
{
var batman = new Batman();
var superman = new Superman();
return superman;
}
I do not know instance of which class the Crossover will return, it could be Batman or Superman.
var someVariableName = Crossover(); //I don't know if this contains an instance of Superman or Batman;
//I do know that no matter which class instance is returned, it will always contain a function named Jump which i want to trigger:
someVariableName.Jump();
Now i know i could do something like:
if (someVariableName.GetType() == typeof(Superman))
{
((Superman) someVariableName).Jump()
}
But is there a way to trigger the Jump function without having to manually check for each type with if..else.., when i know that the instance of the class saved in that variable will always contain a Jump function?
Use an interface:
interface ISuperHero
{
void Jump();
}
class Batman : ISuperHero
{
public void Robin(){...}
public void Jump(){...}
}
class Superman : ISuperHero
{
public void Kryptonie(){...}
public void Jump(){...}
}
Then return the interface from your method:
public ISuperHero Crossover()
This is where interfaces become useful. Consider this interface:
public interface ISuperhero
{
void Jump();
}
And these implementations:
class Batman : ISuperhero
{
public void Robin(){...}
public void Jump(){...}
}
class Superman : ISuperhero
{
public void Kryptonie(){...}
public void Jump(){...}
}
They're individual implementations, but they share a common polymorphic interface. Your function can then return that interface:
public ISuperhero Crossover()
{
var batman = new Batman();
var superman = new Superman();
return superman;
}
Since that interface has a Jump()
method, it can be called directly:
var someVariableName = Crossover();
someVariableName.Jump();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With