Reputation: 1089
Why does testMammal.BreastFeed() called by testMammal not call the BreastFeed method of Mammals class? What is the type of testMammal? Does the left side indicate type or the right side? Mammals testMammal = (aWhale as Mammals)
using System;
using System.Collections.Generic;
namespace ConsoleApplication3
{
class Mammals
{
public string age { get; set; }
public virtual void BreastFeed()
{
Console.WriteLine("This animal Breastfeeds its young ones.");
}
}
class Fish : Mammals
{
public int FinsNum { get; set; }
public override void BreastFeed()
{
Console.WriteLine("This animal Breastfeeds its young ones fish style");
}
}
class Program
{
static void Main(string[] args)
{
Fish aWhale = new Fish();
//Mammals testMammal = (Mammals)aWhale;
Mammals testMammal = (aWhale as Mammals);
testMammal.BreastFeed();
}
}
}
Upvotes: 2
Views: 1369
Reputation: 1529
It may make sense to define your BreastFeed()
method in Mammals
as abstract
. In doing so you do not supply any implementation in the base class, which in this case is Mammals
. It must be overridden in the child class or the program will not compile.
You would also define the class Mammals
as abstract
too.
Abstract methods are overridden in the same way as virtual methods. This may prevent confusion and would highlight any methods forgotten to be overridden by mistake.
Upvotes: 1
Reputation: 12956
Why does testMammal.BreastFeed() called by testMammal not call the BreastFeed method of Mammals class?
testMammal
is a Fish
casted to a Mammals
. BreastFeed()
will be called on Fish
What is the type of testMammal?
Mammals
Does the left side indicate type or the right side?
Left side is the type of the variable. The object that the variable refers to can be a Mammals
or any subclass.
This:
Mammals testMammal = (aWhale as Mammals);
is the same as
Mammals textMammal = new Fish();
The object is a Fish, the variable is of type Mammals. You can only call public members of Mammals
but any overrided members will be Fish's
members.
Upvotes: 1
Reputation: 245399
Your Mammals
class defines BreastFeed()
as a virtual method which means that it can be overridden by its children.
The Fish
class properly overrides that method with its own implementation. That means that any time you instantiate the class and treat it as Fish
or Mammals
, the overriden implementation will be called. That's exactly what an overriden virtual method should do.
If you defined things a little differently and hid the BreastFeed()
method instead of overriding it, you would get the behavior that you're expecting.
Upvotes: 2