I am trying to understand how to use or access multiple classes in C#, can someone explain to me what this code does?
public class Mammal : Animal
{
public Mammal(String name) : base(name) { }
public override void Eat(Food food)
{
Console.WriteLine("Mammal \"" + Name + "\" eats " + food.Name);
}
}
What is the purpose of public override void Eat(Food food)? I mean what does it do??
namespace ConsoleApplication1
{
public class Food
{
private String name;
Food(String name)
{
this.name = name;
}
public String Name
{
get
{
return name;
}
set
{
name = value;
}
}
}
public class Animal
{
private String name = "no name";
public String Name {
get
{
return name;
}
set
{
name = value;
}
}
private Animal() { }
public Animal(String name)
{
this.name = name;
}
public virtual void Eat(Food food)
{
Console.WriteLine("Animal \"" + Name + "\" eats " + food.Name);
}
public virtual void Born()
{
Console.WriteLine("Animal \"" + Name + "\" is born");
}
public virtual void Die()
{
Console.WriteLine("Animal \"" + Name + "\" is died");
}
}
public class Mammal : Animal
{
public Mammal(String name) : base(name) { }
public override void Eat(Food food)
{
Console.WriteLine("Mammal \"" + Name + "\" eats " + food.Name);
}
public override void Born()
{
Console.WriteLine("Mammal \"" + Name + "\" is born");
}
public override void Die()
{
Console.WriteLine("Mammal \"" + Name + "\" is died");
}
public virtual void FedMilk(Mammal[] children)
{
for (Int32 i = 0; i < children.Length; i++)
{
Console.WriteLine("Mammal \"" + Name + "\" feds milk child \"" + children[i].Name + "\"");
}
}
}
public class Horse : Mammal
{
public Horse(String name) : base(name) { }
public override void Eat(Food food)
{
Console.WriteLine("Horse \"" + Name + "\" eats " + food.Name);
}
public override void Born()
{
Console.WriteLine("Horse \"" + Name + "\" is born");
}
}
}
Ok,
You have defined a basic class called mammal and then you created different types of mammals like Animal and then a specific animal (Horse ).
So every mammal needs to eat, so that why you have created a functions called eat..
But every animal which is a mammal eats the same things? NO!!!
But every mammal needs to eats .
So in that place the override attribute comes handy, it allows you to override the basic function of “eat” so you would be able to specified what eats every specific animal.
So when you create a dog class you will override the eat function and specified whom eat some dog food.
But because all of your specific animal are also animals you can refer to them as animals and print the eat function.
lets say you want to see what eats every animal. you will create a loop of a list of animals and print the eat function.
because you have override the eat function and specified every food. you will get the correct food for each animal.
am i making my self clear?
for example see this code