the keyword "new" doesn't change the base class method, while the keyword "override" changes.
We have these code:
class Program
{
static void Main(string[] args)
{
DerivedClass dc = new DerivedClass();
BaseClass bc = new DerivedClass() as BaseClass;
dc.Print();
bc.Print();
}
}
public abstract class BaseClass
{
public virtual void Print()
{
Console.WriteLine("This is base class");
}
}
public class DerivedClass : BaseClass
{
public new void Print()
{
Console.WriteLine("This is derived class");
}
}
The running results are:
This is derived class
This is base class
while if we wrote code below:
class Program
{
static void Main(string[] args)
{
DerivedClass dc = new DerivedClass();
BaseClass bc = new DerivedClass() as BaseClass;
dc.Print();
bc.Print();
}
}
public abstract class BaseClass
{
public virtual void Print()
{
Console.WriteLine("This is base class");
}
}
public class DerivedClass : BaseClass
{
public override void Print()
{
Console.WriteLine("This is derived class");
}
}
The running results are:
This is derived class
This is derived class
No comments:
Post a Comment