Skip to content

Instantly share code, notes, and snippets.

@harshityadav95
Created July 7, 2017 19:53
Show Gist options
  • Save harshityadav95/48c1c0585ad9759e1c8fe24e99fd759c to your computer and use it in GitHub Desktop.
Save harshityadav95/48c1c0585ad9759e1c8fe24e99fd759c to your computer and use it in GitHub Desktop.
C# classes and Inheritance
using System;
namespace After002
{
internal class Program
{
private static void Main(string[] args)
{
var animals = new IAnimal[] {new Monkey(), new Dog()};
foreach (var animal in animals)
{
DisplayAnimalData(animal);
}
}
private static void DisplayAnimalData(IAnimal animal)
{
Console.WriteLine("Animal has {0} legs and makes this sound: {1}", animal.NumberOfLegs);
animal.Vocalize();
}
}
internal interface IAnimal
{
int NumberOfLegs { get; }
void Vocalize();
}
internal abstract class AnimalBase : IAnimal
{
private readonly string _sound;
protected AnimalBase(int numberOfLegs, string sound)
{
NumberOfLegs = numberOfLegs;
_sound = sound;
}
public int NumberOfLegs { get; private set; }
public void Vocalize()
{
Console.WriteLine(_sound);
}
}
internal class Dog : AnimalBase
{
public Dog() : base(4, "woof!")
{
}
}
internal class Monkey : AnimalBase
{
public Monkey() : base(2, "<monkey sound/>!")
{
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment