|
|
Objekt-orientation and Dynamic Binding
Animal.cs
using System;
abstract class Animal {
public abstract string Name { get; }
public abstract void WhoAreYou();
public abstract bool Likes(string food);
public abstract void Speak();
}
class Dog : Animal {
public override string Name { get { return "dog"; } }
public override void WhoAreYou() { Console.WriteLine("I am an animal"); }
public override bool Likes(string food) {
return food == "bones" || food == "meat";
}
public override void Speak() { Console.WriteLine("Wooff"); }
}
class Cat : Animal {
public override string Name { get { return "cat"; } }
public override void WhoAreYou() { Console.WriteLine("I am an animal"); }
public override bool Likes(string food) {
return food == "milk" || food == "fish";
}
public override void Speak() { Console.WriteLine("Meoow"); }
}
class Cow : Animal {
public override string Name { get { return "cow"; } }
public override void WhoAreYou() { Console.WriteLine("I am an animal"); }
public override bool Likes(string food) {
return food == "grass";
}
public override void Speak() { Console.WriteLine("Moooh"); }
}
class Test {
static Animal[] farm = {
new Cow(),
new Dog(),
new Cow(),
new Cat(),
new Cat()
};
public static void Main() {
foreach (Animal a in farm)
if (a.Likes("fish")) a.Speak();
else Console.WriteLine("A " + a.Name + " does not like fish");
}
}
|
|