Home   Cover Cover Cover Cover
 

Abstrakte Klassen

A09.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 a dog"); }
  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 a cat"); }
  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 a cow"); }
  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");
  }
}

Da sämtliche Methoden der Klasse Animal nun abstrakt sind, müssen sie in den Unterklassen überschrieben werden. Man kann also keine Implementierung von der Oberklasse erben.

Da Animal abstrakt ist, darf man außerdem keine Objekte dieser Klasse erzeugen. Es gibt als Cow-, Cat- und Dog-Objekte, aber keine Animal-Objekte.