Abstract classes and virtual methods

Abstract classes can be overridden by virtual methods (true, false)

Questions by Raj_Kumar12

Showing Answers 1 - 8 of 8 Answers

SoCalBruce

  • Dec 3rd, 2007
 

An abstract class can ONLY be overridden by a virtual method.  If the method is not virtual then the abstract method is "hidden".

 

The "override" also means the member is virtual.  For example, Derived.Method is a virtual method:

 
public abstract class Base
{
    public abstract void Method ( );
}
 
public class Derived : Base
{
    public override void Method ( )
    {
    }
}

  Was this answer useful?  Yes

PeterVH

  • Aug 19th, 2011
 

Hello Raj,

you override methods, not classes. So, guessing you mean abstract methods.
The overriding method can NEVER be virtual, but by using the "new" keyword you can *replace* the abstract method, not override. You can override an abstract method with another abstract method however.

Basically:
The overridden base method must be virtual, abstract, or an "override" itself.
The overriding (derived) method cannot use new / static / virtual.

Code
  1.     public abstract class MeaningOfLife

  2.     {

  3.         // The overridden base method must be virtual, abstract, or override.

  4.         public abstract int GiveMeTheMeaningAbstract();

  5.         public virtual int GiveMeTheMeaningVirtual()

  6.         {

  7.             // I don't know, let's just return a random number

  8.             return DateTime.Now.Millisecond;

  9.         }

  10.     }

  11.  

  12.     // could also make this class abstract, but no need for it

  13.     public class AccordingToHitchHikers : MeaningOfLife

  14.     {

  15.         // needs the override to implement, otherwise won't compile

  16.         public override int GiveMeTheMeaningAbstract() { return 42; }

  17.  

  18.         // you can leave out the override here (will compile),

  19.         // but then you aren't overriding but hiding. In that case add "new" keyword

  20.         public override int GiveMeTheMeaningVirtual() { return 42; }

  21.     }

  22.  

  23.     // Needs to be abstract, as it has an abstract member

  24.     public abstract class WhatIsLife : MeaningOfLife

  25.     {

  26.         // you can override an abstract method with another abstract one

  27.         // (for what use I still don't really know..

  28.         public override abstract int GiveMeTheMeaningAbstract();

  29.     }

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions