[Mono-list] Re: Final method in C# (as the final keyword in Java)

Raja R Harinath rharinath at novell.com
Tue May 30 07:47:50 EDT 2006


Hi,

Ympostor <ympostor at clix.pt> writes:

> Raja R Harinath escribió:
[mildly edited quote]
>> Ympostor <ympostor at clix.pt> writes:
>>
>>> Simple question (forgive my ignorance):
>>>
>>>     public abstract class GrandFather { public abstract void DontOverrideMe(); }
>>>     public class Father : GrandFather { public sealed override void DontOverrideMe() { Console.WriteLine("father"); } }
>>>     public class Son : Father { public void DontOverrideMe() { Console.WriteLine("unruly son"); } 
>>>
>>> Why the compiler only gives a warning about Son::DontOverrideMe instead
>>> of an error? And why with a "new" keyword the warning disappears? I want
>>> a non overridable method :(
>> You have a non-overridable method (hint: try using 'override' in
>> 'Son').
>
> I can't override the method in Son with the override keyword, but
> without that keyword I can hide it! So I suppose that doing this:
>
> Son oSon = new Son();
> Son.DontOverrideMe();
>
> The result would be "unruly son".

OK.  That's what the 'new' keyword does.

> I don't want that, I want that all derived classes of Father return "I
> am acting as a father" to the console, and I want the compiler to
> complain if a derived class wants to hide or override the method.

There are two ways to respond.

  1. You can't -- since C# has a special modifier 'new' that allows
     child classes to "escape" the tyranny of parent classes :-)

  2. Why do you care?  If you're using DontOverrideMe polymorphically
     through a 'GrandFather' or 'Father' reference, you'll get the right
     behaviour even with a 'Son' object.

- Hari


More information about the Mono-list mailing list