通过子类调用非抽象方法时出错

时间:2017-12-09 07:02:04

标签: c#-4.0

    class Program
    {
        static void Main(string[] args)
        {
    // in here iam create an instance of child class
            var obj = new dog("meat");
            obj.run();
            obj.sleep();

            Console.ReadLine();

        }
    }
    abstract class animal {
        protected string eating;
        abstract public void sound();

        public void run() {
            Console.WriteLine("Runnig");
        }
        public void sleep()
        {
            Console.WriteLine("sleeping");
        }
    }
    class cat : animal
    {
        public cat(string eat) {
            this.eating = eat;
        }
// this is my child class define parent class method
        protected override void sound()
        {
            Console.WriteLine("Meow");

        }
    }
    class dog : animal{

        public dog(string eat){
            this.eating = eat;
        }
        public override void sound()
        {
            Console.WriteLine("Woof");

        }
    }

//错误:错误1' Abbstraction.cat.sound()':在覆盖' public'时无法更改访问修饰符继承成员' Abbstraction.animal.sound()' E:\ C sharp \ ObjectOrientedConcept \ Abbstraction \ Program.cs 39 33 Abbstraction

1 个答案:

答案 0 :(得分:1)

您可以将sound()中的抽象方法签名abstract class Animal定义为公开。

稍后您尝试将访问修饰符更改为protected。这是不允许的。您必须坚持基类中定义的修饰符。