Overriding and Inheritance in C#

后端 未结 8 2191
时光说笑
时光说笑 2020-12-10 10:49

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

相关标签:
8条回答
  • 2020-12-10 11:23

    You need to use the override keyword to override any virtual or implement any abstract methods.

    public class MoodyObject
    {
        protected virtual String getMood() 
        { 
            return "moody"; 
        }    
        public void queryMood() 
        { 
            Console.WriteLine("I feel " + getMood() + " today!"); 
        }
    }
    
    public class HappyObject : MoodyObject
    {
        protected override string getMood()
        {
            return "happy";
        }
    }
    

    What I would recommend here is that you probally meant for MoodyObject to be an abstract class. (You'd have to change your main method if you do this but you should explore it) Does it really make sense to be in a moody mode? The problem with what we have above is that your HappyObject is not required to provide an implementation for getMood.By making a class abstract it does several things:

    1. You cannot new up an instance of an abstract class. You have to use a child class.
    2. You can force derived children to implement certain methods.

    So to do this you end up:

    public abstract class MoodyObject
    {
        protected abstract String getMood();
    
        public void queryMood() 
        { 
            Console.WriteLine("I feel " + getMood() + " today!"); 
        }
    }
    

    Note how you no longer provide an implementation for getMood.

    0 讨论(0)
  • 2020-12-10 11:23

    You need to tell C# that your object is overriding the function from the base class.

    Here is the MSDN article about the syntax you need: http://msdn.microsoft.com/en-us/library/ebca9ah3(VS.71).aspx

    public class SadObject: MoodyObject    
    {        
        override String getMood()
    
    0 讨论(0)
提交回复
热议问题