Asked By
nadeemrao
0 points
N/A
Posted on - 08/09/2011
Has anyone or anyone you know experienced a situation where a class could be inherited from some other class, but its methods cannot be over ridden?
If yes, how then did you/they achieve this functionality; because I am stuck with the same situation and looking for answers?
Answered By
andre
0 points
N/A
#92839
How will Calling base class constructor?
Yes!
In order to deal with this kind of situation, you have to inherit your constructors from base class.
In this case, you will be able to restrict your methods to be over-ridden. I do not think that there are any other ways to handle this.
Put colon sign after inherited class constructor and specify base class constructor there.
How will Calling base class constructor?
Hello Nadeemrao,
Well, before answering your question I would like to give some notions about POO in C# (same for Vb.net)
-
A class preceded by the keyword class wouldn't be initiated.
-
If a class is  preceded by the keyword "Sealed" that means no other class can inherit from this class.
No, if you avoid using the "Sealed"Â keyword you can have a class which can be initiated.
But you want to have some methods that can be overridden? Well It's simple! You only have to use the keyword "virtual".
For instance, you have to override the class display
public virtual string Display(double Diameter)
{
return Var1+var2;
}
Now we try to override this method within a class which has inherited from our base class
So the display should be in a different way to make sense
overridden public  string Display(double Diameter)
{
return "("+Var1+var2+var3+")";
}
 That's how you could have overridden methods within a base class: just use "virtual" keyword.
How will Calling base class constructor?
Hi Nadeemrao
I hope I have got exactly what you need as the post subject doesn't match the content of the message itself anyway.
Every method in a parent class can be overridden inside the child class even if it has the keyword Virtual in its signature. If it doesn't and you tried to override it in the child class, you will get a compile error.
Example:
class A
{
public virtual void OverridenMethod()
{ }
public void NotOverridenMethod()
{ }
}
class B : A
{
public override void OverridenMethod()
{ }
public override void NotOverridenMethod()
{ }
}
The first one will be overridden, but the second one will not and you will get the following error:
Error 1 'Inheritance.Program.B.NotOverridenMethod()': cannot override inherited member 'Inheritance.Program.A.NotOverridenMethod()' because it is not marked virtual, abstract, or override C:UsersymohammedDesktopInheritanceInheritanceProgram.cs 23 34 Inheritance
Â
Hope that my answer got you unstuck, and if there is any other problem, please don't hesitate to contact me.
Best Regards,
Nora.