1、重载(overload)
public void Sleep() { Console.WriteLine("Animal睡觉"); } public int Sleep(int time) { Console.WriteLine("Animal{0}点睡觉", time); return time; }
2、重写(override)
public virtual void EatFood() { Console.WriteLine("Animal吃东西"); } public override void EatFood() { Console.WriteLine("Cat吃东西"); //base.EatFood(); }
3、虚方法:即为基类中定义的允许在派生类中重写的方法,使用virtual关键字定义
在派生类中通过override重载该方法,通过基类变量引用派生类对象,来访问派生类中重载的这个同名方法
class Shape { private int x; private int y; public Shape(int sx,int sy) { x=sx; y=xy; } public virtual float Area() { return 0.0f } } class Rectangle:Shape { private int w; private int h; public Rectangle(int rx,int ry ,int rw,int rh):base(rx,ry)--调用父类的方法 --this 则是调用自己的方法 { w=rw; h=rh; } pulic override float Area() { return w*h; } } class Program { static void Main(string[] args) { Shape myshape; Rectangle r = new Rectangle (2,2,10,26); myshape=r; console.writeline(myshape.Area());//父类变量引用子类的对象,调用子类中的同名方法 } }