简体   繁体   中英

virtual/override, new and not specified

I get the difference between virtual/override and new modifiers. But what about times when I don't specify any modifiers.

For example I have Animal and Cat classes ( Cat inherits Animal ).

Animal class has method:

public void Say()
{
    // do something
}

And Cat class has method:

public void Say()
{
    // do something else
}

When I'm working with this methods they work as if I used new keyword.

Visual Studio shows me a warning (Use new keyword if hiding was intended).

Why does compiler won't break when I don't specify keyword. It just magically works with a little warning. Can I use some strict mode or may be edit settings in IDE.

Or may be it's a feature that I don't get :)

Why does compiler won't break when I don't specify keyword.

To avoid the "brittle base class" problem - where Cat originally has the Say() method, and then the author of Animal wants to add a Say() method too. With the current approach, that is not a breaking change - it will create a warning for the author of Cat , but that's all. The behaviour of all code will stay the same. The author of Cat can then decide what to do about their Say method - add the new modifier, or override Animal.Say() if that's virtual, or potentially rename the method to avoid confusion (if they control all clients as well).

For Animal class public virtual void Say() . For Cat public override void Say() . Then always define object of type Animal:

Animal my_cat = new Cat();
my_cat.Say();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM