Ok, bear with me guys and girls as I\'m learning. Here\'s my question.
I can\'t figure out why I can\'t override a method from a parent class. Here\'s the code fro
If you want to override a base class method, it needs to be declared as virtual
. The overriding method in a derived class has to be explicitly declared as override
. This should work:
public class BaseObject
{
protected virtual String getMood()
{
return "Base mood";
}
//...
}
public class DerivedObject: BaseObject
{
protected override String getMood()
{
return "Derived mood";
}
//...
}
Edit: I just tried it in a c# console application, and it compiles. So the source code you use should differ in some tiny but important piece from what you posted here.
My program.cs is this:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// leaving out your implementation to save space...
}
}
public class SadObject : MoodyObject
{
protected override String getMood()
{
return "sad";
}
//specialization
public void cry()
{
Console.WriteLine("wah...boohoo");
}
}
public class HappyObject : MoodyObject
{
protected override String getMood()
{
return "happy";
}
public void laugh()
{
Console.WriteLine("hehehehehehe.");
}
}
}