using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
/// <summary>
/// 多态项目学习
/// </summary>
class Program
{
static void Main(string[] args)
{
Animal myPet1 = new Bird("Polly");
myPet1.ShowType();
Animal myPet2 = new Dog("Tom");
myPet2.ShowType();
Animal myPet3 = new Chicken("Terry");
myPet3.ShowType();
}
}
public abstract class Animal
{
public abstract void ShowType();
}
public class Bird : Animal
{
private string type;
public Bird()
{
}
public Bird(string myType)
{
this.type = myType;
}
public override void ShowType()
{
Console.WriteLine("fly,the type is {0}",type);
}
}
public class Dog : Animal
{
private string type;
public Dog()
{
}
public Dog(string myType)
{
this.type = myType;
}
public override void ShowType()
{
Console.WriteLine("bak,the type is {0}",type);
}
}
public class Chicken :Dog //如果在这是继承自Animal类,则会提示出错因为这里没有实现抽象成员却要去调用他,若用Virtual则不会。
{
public string type;
public Chicken()
{ }
public Chicken(string myType)
{
this.type = myType;
}
/// <summary>
/// 在这里用new关键字覆盖了抽象函数所以只能显示到fly,the type is
/// </summary>
public new void ShowType()
{
Console.WriteLine("gege,the type is {0}", type);
}
}
}
总结:
多态:就是使对象在不同的时候呈现出不同的行为
抽象类:被关键字abstract修饰的类称为抽象类
抽象类里面定义着一个抽象函数,抽象函数也是有abstract关键字定义的。
1)在继承抽象类时,必须覆盖该类中的每一个抽象方法,而每个已实现的方法必须和抽象类中指定的方法一样,接收相同数目和类型的参数,具有同样的返回值,这一点与接口相同。 2)当父类已有实际功能的方法时,该方法在子类中可以不必实现,直接引用的方法,子类也可以重写该父类的方法(继承的概念)。
上面的列子: Animal myPet1实际上是生命一个myPet1的指针,然后将该指针指向一个类型为Bird的类型区域。而override关键字只是覆盖的员类抽象类的函数,实现自己的逻辑。因此这样会调用到Bird的ShowType函数。而使用new关键字会新生称一个函数,这样其父类方法排在前面而其子类方法排在后面。而不同类型的指针对虚拟方法表的访问有不同的访问标识(一个偏移地址来标识这个)。这样就会访问到不同的方法。
(3)使用virtual也是可以的,不过不同的是virtual生命的不用在抽象类中,而且在virtual声明下可以实现函数。
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Class1
{
static void Main(string[] args)
{
Animal myPet1 = new Bird("Polly");
myPet1.ShowType();
Animal myPet2 = new Dog("Tom");
myPet2.ShowType();
Animal myPet3 = new Chicken("Terry");
myPet3.ShowType();
Chicken myPet4 = new Chicken("Terry");
myPet4.ShowType();
}
}
public class Animal
{
public virtual void ShowType()
{
Console.WriteLine("the type is Animal");
}
}
public class Bird : Animal
{
private string type;
public Bird()
{
}
public Bird(string myType)
{
this.type = myType;
}
public override void ShowType()
{
Console.WriteLine("fly,the type is {0}", type);
}
}
public class Dog : Animal
{
private string type;
public Dog()
{
}
public Dog(string myType)
{
this.type = myType;
}
public override void ShowType()
{
Console.WriteLine("bak,the type is {0}", type);
}
}
public class Chicken : Animal
{
public string type;
public Chicken()
{ }
public Chicken(string myType)
{
this.type = myType;
}
/// <summary>
/// 在这里用new关键字覆盖了抽象函数所以只能显示到fly,the type is
/// </summary>
public new void ShowType()
{
//base.ShowType();
// Console.WriteLine("gege,the type is {0}", type);
}
}
}