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.
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."); }
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With