Can you allow a class to be inherited, but prevent the method from being overridden?

 Posted by Ddd on 2/8/2011 | Category: C# Interview questions | Views: 9401 | Points: 40
Answer:

Yes, put 2 modifers before the method sealed override

ex:
class A
{
public virtual void demo()
{
}
}

class B:A
{
public sealed override void demo()
{
}
}
//Class B can be inherited in C, but demo() method cannot be overriden further
class C:B
{


}


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Posted by: Naimishforu on: 2/9/2011 | Points: 10
sealed override??

Can you please describe sealed override!!

Thanks
Posted by: Ddd on: 2/9/2011 | Points: 10
sealed override:

sealed: It is usually done for a class to prevent it from being inherited.

for a method, sealed would mean that it cannot be overriden further.

we have to use the sealed and override keyword together to prevent the method

overriding.

Thanks.
Posted by: Naimishforu on: 2/9/2011 | Points: 10
What if I only provide sealed to method only?? why do I need to provide override??
Posted by: Ddd on: 2/9/2011 | Points: 10
If you provide sealed to method only and not override, the compiler will generate this error.

B.demo()' cannot be sealed because it is not an override

You can try it in your Visual studio Editor. I'm not going to discuss it any further,

Posted by: Naimishforu on: 2/9/2011 | Points: 10
Ok, Thanks

Login to post response