33
loading...
This website collects cookies to deliver better user experience
public class Bird
{
// whatever properties do birds have
public BirdType Type { get; set; }
}
public enum BirdType
{
African,
American,
European
}
public class Bird
{
// whatever properties do birds have
public BirdType Type { get; set; }
public double GetSpeed()
{
switch(Type)
{
case African:
// logic for African birds
case American:
// logic for American birds
case European:
// logic for European birds
default:
// default logic
}
}
}
public enum BirdType
{
African,
American,
European,
Asian // new type
}
switch
statement" you might say. You could do that, yes, but bear in mind that this will violate SOLID's Open-Closed Principle! And we don't want that, do we?Bird
class, but with one change:public abstract class Bird
{
public abstract double GetSpeed();
}
abstract
modifier to the GetSpeed
method and the Bird
class itself. What that means is that the Bird
class itself has no implementation for that method, nor can it be directly instantiated, and any subclasses might implement it themselves. Now all we gotta do is implement the subclasses!public class AfricanBird : Bird
{
public override double GetSpeed()
{
// logic for African birds
}
}
public class AmericanBird : Bird
{
public override double GetSpeed()
{
// logic for American birds
}
}
public class EuropeanBird : Bird
{
public override double GetSpeed()
{
// logic for European birds
}
}
// Ran on C# Interactive via VisualStudio
> public abstract class Bird
. {
. public abstract double GetSpeed();
. }
> public class AfricanBird : Bird
. {
. public override double GetSpeed()
. {
. return 1;
. }
. }
> public class AmericanBird : Bird
. {
. public override double GetSpeed()
. {
. return 0.7;
. }
. }
> Bird africanBird = new AfricanBird();
> Bird americanBird = new AmericanBird();
> africanBird.GetSpeed()
1
> americanBird.GetSpeed()
0.7
Bird
, we could define the variables as the base class and still use it, and we got our desired result 😉