I have a litte confusion regarding method overriding and the validity of OOP priciples. I know everything regarding sealing, shadowing, overriding, virtual etc. but I came across a scenario, that just confused me. Suppose I have:
class classA
{
public virtual void sayhello()
{
Console.WriteLine("hello I'm A");
}
};
class classB :classA
{
public override void sayhello()
{
Console.WriteLine("hello I'm B");
}
};
class Program
{
static void Main(string[] args)
{
classB a = new classB();
a.sayhello();
}
}
According to everything I studied so far, a method declared as virtual or abstract (in abstract class) can be overriden using override keyword in child class. according to this, above code works perfect. When I remove the virtual keyword, and then try to override the method using override keyword, then compiler gives error as:
cannot override inherited member 'inheritence.classA.sayhello()' because it is not marked virtual, abstract, or override
and then i removed the override key word, from child class, and provided the implementation as:
class classB :classA
{
public void sayhello()
{
Console.WriteLine("hello I'm B");
}
};
In this case, the method could be overrided. I'm able to override the method, which is not virtual or abstract. so, my question is:
1. Did it not violate the OOP principle? since I'm able to override the method, which is not marked as virtual in parent.
2. Why am I allowed to override the method this way? which is not even marked virtual?
3. Removing virtual keyword from classA method, it gave me the feeling of sealed method in classA, when I tried to override that method in classB. (as I mentioned the compiler error earlier). If i remove virtual, so that the child class may not override it, then WHY could the child class cleverly override it, removing its override keyword? Is this ONLY the case, sealed keyword is designed for?
classB
– Pearla
. – WoodbridgeclassB
hides the one inclassA
. That is not overriding. It is just two unrelated methods with the same name. Avoid that; it leads to confusion. – Portent