(1)override关键字实现多态—子类重写父类中virtual关键字的的方法(看例子)。
(2)多层继承中也可以实现多态.即,B类继承A类,C类继承B类(看例子)。
不管继承了多少层,都可以在子类中对父类中已经重写的方法继续进行重写,即如果父类方法用override修饰,如果子类继承了该方法,也可以用override修饰,多层继承中的多态就是这样实现的。要想终止这种重写,只需重写方法时用sealed关键字进行修饰即可。
(3)abstract-override实现多态
让我们通过例子来更深刻的理解:
例子:
(1)
namespace 多态
{
class Fruit
{
public virtual void IFruit()
{
Console.WriteLine("学敏,我是水果");
}
}
class Apple : Fruit
{
public override void IFruit()
{
Console.WriteLine("学敏,我是苹果");
}
}
class Pear : Fruit
{
public override void IFruit()
{
Console.WriteLine("学敏,我是大鸭梨");
}
}
class Program
{
static void Main(string[] args)
{
Fruit [] fruit=new Fruit [3];
fruit [0]=new Fruit();
fruit [1]=new Apple ();
fruit [2] = new Pear();
for (int i=0;i<fruit.Length ;i++)
{
fruit[i].IFruit ();
}
}
}
}
运行结果:
(2)
namespace 多态2
{
class Fruit
{
public virtual void IFruit()
{
Console.WriteLine("学敏,我是水果");
}
}
class Apple : Fruit
{
public override void IFruit()
{
Console.WriteLine("学敏,我是大苹果");
}
}
class RedApple : Apple
{
public override void IFruit()
{
Console.WriteLine("学敏,我是红苹果");
}
}
class Program
{
static void Main(string[] args)
{
Fruit[] fruit = new Fruit[3];
fruit [0]=new Fruit() ;
fruit [1]=new Apple() ;
fruit [2]=new RedApple() ;
for (int i = 0; i < fruit.Length; i++)
{
fruit[i].IFruit();
}
}
}
}
运行结果:
(3)
namespace 多态3
{
abstract class Fruit
{
public abstract void IFruit();
}
class Apple : Fruit
{
public override void IFruit()
{
Console.WriteLine("学敏,我是苹果");
}
}
class Pear : Fruit
{
public override void IFruit()
{
Console.WriteLine("学敏,我是大鸭梨");
}
}
class yellowPear : Fruit
{
public override void IFruit()
{
Console.WriteLine("学敏,我是黄梨");
}
}
class Program
{
static void Main(string[] args)
{
Fruit[] fruit = new Fruit[3];
fruit[0] = new Apple();
fruit[1] = new Pear();
fruit[2] = new yellowPear();
for (int i = 0; i < fruit.Length; i++)
{
fruit[i].IFruit();
}
}
}
}
运行结果: