#679 – Hide An Inherited Method with A Virtual Method

You typically hide an inherited method using the new keyword, indicating that the method should not behave polymorphically.  If you later inherit this method in a subclass, you won’t be able to override the method marked as new.

For example:

  • virtual Dog.Bark  – can override
  • new Terrier.Bark – hides Dog.Bark
  • new Yorkshire.Bark – must hide, can’t override

However, if you want to hide an inherited method, but still allow overriding in a subclass, you can use the virtual new combination:

  • virtual Dog.Bark – can override
  • virtual new Terrier.Bark – hides Dog.Bark, but allows overriding
  • override Yorkshire.Bark – overrides Terrier.Bark

In this case, Terrier and Yorkshire objects referenced by variables of type Dog will not behave polymorphically.  But a Yorkshire object referenced by a Terrier variable will behave polymorphically.

 

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a comment