Monday 11 January 2016

C# Illustrating Object Orientated Programming

On many occassions I have been asked to describe and illustrate Object Orientated Programming.

I struggle to how to describe this in average person terms.
Recently I was asked to write classes for Animal, Dog and Cat

Initially the classes

public class Animal
{
}
public class Dog : Animal
{
}
public class Cat : Animal
{
}

Then provide the following attributes.
Name Property for all Animals
MakeSound method for all whereby Dog returns "Woof" and Cat returns "Miaow" but extensible by using abstract.

The modifications were made below.

public abstract class Animal
{
    public string Name { get; set; }
    public abstract string MakeSound();
}
public class Dog : Animal
{
    public override string MakeSound()
    {
        return "Woof"
    }
}
public class Cat : Animal
{
    public override string MakeSound()
    {
        return "Miaow"
    }
}


Finally suppose you want a generic sound for all animals allowing for instance a Rabbit where the response is unknown so generically speaking its an animal and it makes a noise.

The modifications were made below.

public abstract class Animal
{
    public string Name { get; set; }
    public string MakeSound()
    {
        return "Noise";
    }
}
public class Dog : Animal
{
    public override string MakeSound()
    {
        return "Woof"
    }
}
public class Cat : Animal
{
    public override string MakeSound()
    {
        return "Miaow"
    }
}
public class Rabbit : Animal
{

}


This should help someone explain OO principles with a real life example.


No comments:

Post a Comment