Class Inheritance/Method Override

[亡魂溺海] 提交于 2019-11-30 23:18:42

Since Speak() was originally public, you need to keep it public. You "cannot change access modifier" (public vs private).

Also, you cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override.

Take a read: http://msdn.microsoft.com/en-us/library/ebca9ah3(v=vs.100).aspx

The Speak method will have to be virtual in your base class to override

Pet class

  public virtual void speak(string s)
  {
      s = "Speak";
      MessageBox.Show(s);
  }

and you must use the same modifier (public)

Dog Class

  public override void speak(string s)
  {
     base.speak(s);
  }
protected override void speak()
    {

    }

Pretty sure it is because you are changing a public method to protected in the subclass.

There error is telling you that you cannot change the type of access when overriding the method. So, to fix this just keep the method as public in Cat and Dog:

public override void speak()
    {

    }

Well, the reason why you are getting that error is that you are inheriting the "speak" method from the parent class Pet. You have declared speak() method as a public method and then you are inheriting it and making in protected. I suggest you leave it public once you inherit that and override that in the class Dog, Cat, Monkey.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!