繼承的筆記
来源:互联网 发布:学软件要多久 编辑:程序博客网 时间:2024/06/02 22:45
繼承的一些東西,記錄下。
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(); } }}結果:
Type is Bird
Animal always eat.
Animal always eat.
Colot is
Type is Chicken:
Animal Always eat.
Type is Chicken
1.對象的創建,首先是字段,會先找到不斷的遞歸找到父類的字段,為其分配內存空間,字段的存儲是由上到下排列的,最高層類的字段在最前面。然後是方法表。方法表是限於對象存在的。這個方法表在類第一次加載到AppDomain的時候就完成了。而對象創建的時候只是指向方法表上的地址。方法表的創建也是父類先子類后。
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的方法。又一次說明了引用類型的區別決定不同的對象在方法裱中的訪問權限。