-------------------------- ASP.Net+Android+IOS开发、.Net培训、期待与您交流! --------------------------
一、单词释义
virtual
adj. | 实质上的,事实上的;(计算机)虚拟的;<物>有效的,虚像的; |
vt. | 推翻,无视;践踏;优先于;覆盖 |
n. | 佣金;超驰控制装置;撤消,推翻
|
如果能很好的理解关键字的英文原义,那么它们在编程中起的作用就很好理解了。
二、多态的实现
通过继承实现的不同对象调用相同的方法,表现出不同的行为,称之为多态。
要对一个类中一个方法用
override
修饰,该类必须从父类中继承了一个对应的用
virtual
修饰的虚拟方法,否则编译器将报错。
public class Athlete
{
public virtual void Play()
{
Console.WriteLine(" doing sports");
}
}
public class FootballPlayer : Athlete
{
public override void play()
{
Console.WriteLine("Playing Football");
}
}
public class Striker : FootballPlayer
{
public override void play()
{
Console.WriteLine("Great chance,shoot!");
}
}
class Tester
{
static void Main(string[] args)
{
Animal[] Athlete = new Athlete[3];
Athlete[0] =newAthlete();
{
public virtual void Play()
{
Console.WriteLine(" doing sports");
}
}
public class FootballPlayer : Athlete
{
public override void play()
{
Console.WriteLine("Playing Football");
}
}
public class Striker : FootballPlayer
{
public override void play()
{
Console.WriteLine("Great chance,shoot!");
}
}
class Tester
{
static void Main(string[] args)
{
Animal[] Athlete = new Athlete[3];
Athlete[0] =newAthlete();
Athlete[1] =new FootballPlayer();
Athlete[2] =new Striker();
for (int i = 0; i < 3; i++ )
{
Athlete[i].Play();
}
}
}
for (int i = 0; i < 3; i++ )
{
Athlete[i].Play();
}
}
}