繼承的筆記

繼承的一些東西,記錄下。
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的方法。又一次說明了引用類型的區別決定不同的對象在方法裱中的訪問權限。
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值