1)所处位置不同 重载在同类中 重写在父子类中
2)定义方式不同 重载方法名相同 参数列表不同 重写方法名和参数列表都相同
3)调用方式不同 重载使用相同对象以不同参数调用 重写用不同对象以相同参数调用
4)多态时机不同 重载时编译时多态 重写是运行时多态
重载:
class OverLoadTest
{
public void Hello()
{
}
public void Hello(string str)
{
}
public string Hello()
{
}
}
重写:
重写发生在有继承关系的类之间
重写发生在派生类上,通过override关键字来改写从其父类继承过来的具有相同返回值,方法名称和参数列表的方法。
class Program
{
static void Main(string[] args)
{
OverWriteTestTT owTT = new OverWriteTestTT();
owTT.Hello();
overWriteTestTTT owTTT = new overWriteTestTTT();
owTTT.Hello();
}
}
class OverWriteTest
{
//Over write the method ToString();
public override string ToString()
{
return "hello world";
}
//Define a virtual method Hello() to be over written
public virtual void Hello()
{
Console.WriteLine("hello");
}
}
class OverWriteTestTT : OverWriteTest
{
public override void Hello()
{
Console.WriteLine("No hello world");
}
}
class overWriteTestTTT : OverWriteTestTT
{
//Over write the method Hello() of class OverWriteTestTT
public override void Hello()
{
base.Hello();
Console.WriteLine("NNo hello world");
}
}