public class Shapes
{
public virtual void Color()
{
Console.WriteLine("Shapes");
}
}
public class Square : Shapes
{
public void Color()
{
Console.WriteLine("Square");
}
}
public class Test
{
public static void main()
{
Shapes s1 = new Shapes();
s1.Color();
Shapes s2 = new Square();
s2.Color();
}
}
I want to know if the base class has defined some methods virtual, then is it mandatory to override them in derive class? Similarly, If the base class method is abstract, we need to implement the method in derive class, but is override modifier is mandatory? What if override modifier is omitted.
Definitely not. It is up to the derived class to decide whether or not to override the virtual method. Note that some classes will recommend that derived classes override a particular virtual method in some cases, but the compiler will not enforce that.
Yes, you need to use the
overridekeyword, otherwise the method will be hidden by the definition in the derived class.If you actually run your code, you will see “Shapes” printed twice. That’s because the
Color()method in theSquaresclass isn’t declared using theoverridekeyword. As such, it hides the base class method. This means it will only be accessible through a variable of typeSquares:This will print “Square”, since you’re calling the method on a variable of the correct type.