using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Bird bird = new Bird();
bird.ShowType();
bird.Eat();
Chicken chicken = new Chicken();
chicken.Eat();
chicken.ShowColor();
chicken.ShowType();
Bird bird2 = new Chicken();
bird2.Eat();
bird2.ShowType();
}
}
public abstract class Animal
{
public abstract void ShowType();
public void Eat()
{
Console.WriteLine("Animal always eat.");
Console.ReadLine();
}
}
public class Bird : Animal
{
private string type = "Bird";
public override void ShowType()
{
//throw new NotImplementedException();
Console.WriteLine("Type is {0}",type);
Console.ReadLine();
}
private string color;
public string Color
{
get { return color; }
set { color = value; }
}
}
public class Chicken : Bird
{
private string type = "Chicken";
public override void ShowType()
{
Console.WriteLine("Type is {0}:",type);
Console.ReadLine();
}
public void ShowColor()
{
Console.WriteLine("Color is {0}",Color);
Console.ReadLine();
}
}
}
結果:
2.下面重點看看Chicken chicken = new Chicken();與Bird bird2 = new Chicken(); 這裡這兩個對象在內存的分佈上是一樣的。都創建了chicken類型的對象。區別就在於其引用指針類型不同。bird2為Bird類型的指針,而chicken為Chicken類型的指針,那麼之後再調用方法的時候將會有筆筒的方位權限。比如說,bird2就不能調用showcolor這個方法。再看看shotype方法。chicken.ShowType()的結果是"Type is Chicken:",而bird2.ShowType();的結果是“Type is Chicken”。明顯看出了,bird2調用的是Bird類中的方法。而chicken調用的是Chicken的方法。又一次說明了引用類型的區別決定不同的對象在方法裱中的訪問權限。