简体   繁体   中英

Understanding how to use classes

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

List<Animal> animals = new List<Animal>();

            Horse hr = new Horse();
            Dog dg = new Dog();
            Bird br = new Bird();

            animals.Add(hr);
            animals.Add(dg);
            animals.Add(br);

            foreach(var animal in Animals)
            {
                Console.WriteLine(animal.eat());
            }

override is a keyword in C# that says "Hey, I want to do this thing differently than my base (parent) class." It has to do with polymorphism .

In the case of the code posted, you have a class hierarchy . A Mammal is a specific type of Animal . So we can say Mammal inherits from the Animal base class ( Mammal : Animal ).

In the Animal base class, there are virtual members (like public virtual void Eat ). Any of these virtual members can be overridden in a more derived class.

When you override a virtual property or method in a more derived class, you are saying "When someone uses this property or method, do it differently if the object is an instance of Mammal than you would if the instance was a basic Animal, or some other kind of Animal (such as a Bird, Fish, or Reptile)".

Animal beaver = new Mammal("beaver"); // "Mammal beaver"
Animal finch = new Bird("finch"); // "Bird finch"
Animal japaneseHuman = new Mammal("Japanese human"); // "Mammal Japanese human"
Animal godzilla = new Reptile("godzilla"); // "Reptile godzilla"

beaver.Eat(new Food("wood")); // "eats wood"
finch.Eat(new Food("nuts")); // "eats nuts"
japaneseHuman.Eat(new Food("whale")); // "eats whale"
godzilla.Eat(new Food("Japanese people")); // "eats Japanese people"

You can also override types that are declared as abstract in an abstract base class. Overriding abstract works almost just like overriding virtual , except that there is no base implementation defined (only the base signature is defined).

The override provides the ability for a class to change how a specific method is implemented.

From reading the sample code, all Animal s can be born, can die, and can eat food. The overrides in the Mammal and Horse classes allow for different functionality. The way a Horse eats can be different different to how a Dog eats.

The fact that the methods are virtual allow for ode such as :

Animal[] animals = new Animal[] { new Horse(), new Dog(), new Mammal() };
foreach (Animal animal in animals)
{
    animal.Born();
    animal.Eat(new Food());
    animal.Die();
}

Each of the calls above flow down and will call the Horse.Born() or Dog.Eat(Food) implementations.

Blockquote what is the purpose of public override void Eat(Food food) i mean what does it do??

Mammals is a class of type Animal. Mammal will inherit all the properties and methods Animal has and must have implementations for everything that's abstract in Animal if Animal is an abstract class. All abstract means is that it's merely a skeleton to force the subclasses to implement things the abstract class knows they must have in order to function properly.

Mammals has a method, Food, that is specific to its class and noted to be different than what all the other animals do. Even though all animals may have a method in the base class animal defined for food, mammals will always use its own method--that's what override means.

So to review:

Mammal someMammal = new Mammal();
someMammal.Eat(new Food());

the version of eat that will be called is Mammal's Eat in this case.

Now if we did this:

Animal someAnimal = new Animal();--must be non-abstract
someaAnimal.Eat(new Food());

here we call animal's version of Eat.

Now what if we did this?

Mammal someMammal = new Mammal();
someMammal.Eat(new Food());--no surprise we get mammal's eat
Animal someAnimal = (Animal)someMammal;
someAnimal.Eat(new Food());--but what happens here!?

Well, because Mammal's eat is an override, the mammal eat method will be called again. Had it not been override, we would have gotten Animal's.

for reference, to learn more about override, base/derived classes, and virtual classes. http://msdn.microsoft.com/en-us/library/ms173152%28v=vs.80%29.aspx

what is the purpose of public override void Eat(Food food) i mean what does it do??

In the base class, the Eat method has been marked as virtual. This means that it can be reimplemented by any class that inherits it. That is what this bit of code does:

public override void Eat(Food food)

It defines the Eat method for the inheriting class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM