Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

novice inheritance question

Tags:

c#

inheritance

I don't understand why my output is not how I think it should be. I think that it should be Dog barks line break Cat meows. But there is nothing there.

Code:

namespace ConsoleApplication2
{
  class Program
  {
    static void Main(string[] args)
    {
      Pets pet1 = new Dog();
      Pets pet2 = new Cat();
      pet1.Say();
      pet2.Say();
      Console.ReadKey();
    }
  }

  class Pets
  {
   public void Say() { }
  }

  class Dog : Pets
  {
   new public void Say() { Console.WriteLine("Dog barks."); }
  }

  class Cat : Pets 
  {
   new public void Say() { Console.WriteLine("Cat meows."); }
  }
}

I have tried to go through the c# programming guide on MSDN but I find it very difficult to understand some of the examples on there. If someone could link to a good "inheritance for dummies" site, it would be much appreciated.

like image 271
Jim Avatar asked Aug 16 '10 16:08

Jim


2 Answers

Make the Say function in your base class virtual and then override this function in your derived classes:

namespace ConsoleApplication2
{
  class Program
  {
    static void Main(string[] args)
    {
      Pets pet1 = new Dog();
      Pets pet2 = new Cat();
      pet1.Say();
      pet2.Say();
      Console.ReadKey();
    }
  }

  class Pets
  {
   public virtual void Say() {
      Console.WriteLine("Pet makes generic noise");
 }
  }

  class Dog : Pets
  {
    public override void Say() { Console.WriteLine("Dog barks."); }
  }

  class Cat : Pets 
  {
    public override void Say() { Console.WriteLine("Cat meows."); }
  }
}
like image 178
fletcher Avatar answered Oct 05 '22 20:10

fletcher


The new modifier as you've written it:

class Dog : Pets
{
 new public void Say() { Console.WriteLine("Dog barks."); }
}

essentially means that the Say method you've defined is only called when that instance is used as an instance of Dog.

So

Dog dog = new Dog();
dog.Say(); // barks (calls Dog.Say)
Pet pet = dog;
pet.Say(); // nothing (calls Pet.Say)

That explains why you received the results you have; for what you wanted, use virtual methods -- @fletcher's answer explains it well.

like image 38
Mark Rushakoff Avatar answered Oct 05 '22 20:10

Mark Rushakoff