Overriding and Inheritance in C#

后端 未结 8 2192
时光说笑
时光说笑 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:11

    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.");
            }
        }
    }
    

提交回复
热议问题