I am new to C# (coming from C++)
Can I declare a method to be
virtual
andoverride
?(In C++ the method can be virtual in base and derived class as well)The explanation about
new
method keyword in my textbook says:
Sometimes you may want to create your own implementation of a method that exists in a base class. The Line class does this by declaring its own print() method. The Line print() method hides the DrawingObject print() method. The effect is the Parent print() method will not be called, unless we do something special to make sure it is called. Notice the new modifier on the Line class print() method. This enables this method to hide the DrawingObject class print() method and explicitly states your intention that you don't want polymorphism to occur. Without the new modifier, the compiler will produce a warning to draw your attention to this.
What is the influence of it if?
- The base class method is virtual and the derived new?
- The base class method is not virtual and the derived is new?
- What happens if I don`t use new keyword for the method in derived class
- How does polymorphism happen if the method is not virtual in the base class?
- Why "Without the new modifier, the compiler will produce a warning"?
The questions refer the following code.
using System;
public class DrawingObject
{
public virtual void Draw()
{
Console.WriteLine("I'm just a generic drawing object.");
}
public void print()
{
Console.WriteLine("I'm a Parent Class.");
}
}
public class Line : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I'm a Line.");
}
public new void print()
{
base.print();
Console.WriteLine("I'm a Child Class.");
}
}
public class Circle : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I'm a Circle.");
}
}
public class Square : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I'm a Square.");
}
}