C#抽象类,接口

抽象类和接口有很多相似的特性,都是将方法或属性抽象出来,再由派生类详细实现。

用法上接口用于规范,抽象类用于共性,详见——

https://www.cnblogs.com/sunzhenyong/p/3814910.html

实例:

    //抽象类
    //有抽象方法的一定是抽象类
    //抽象类中可以包含普通方法
    public abstract class Fruit
    {
        protected string _chandi; 
        //抽象方法(必须公有)
        public abstract int price();
        //抽象属性(必须公有)
        public abstract string chandi { get; set; }
        //普通方法
        public string desc() { return "水果类"; }
    }
    //继承抽象类,必须实现接口类的所有抽象方法
    public class Apple:Fruit
    {
        //重写抽象方法
        public override int price()
        {
            return 10;
        }
        public override string chandi
        {
            get
            {
                return _chandi;
            }
            set
            {
                _chandi = value;
            }
        }
    }
    //抽象类可继承抽象类并不需要实现父类的方法
    public abstract class Orange : Fruit
    {
        public abstract int pinzhong();
    }

    //==============================================
    //接口
    //不能有构造函数
    public interface Animal
    {
        void age();
        //接口中可以定义属性
        string name { get; set; }
    }

    //必须实现接口的所有属性和方法
    //通过接口可以实现多重继承
    public class Dog:Animal
    {
        string _name;
        public void age()
        {
            Console.WriteLine("age is 1");
        }
        public string name { get {return _name; } set {_name = value; } }
    }
    //==================================================
    class Program
    {
        static void Main(string[] args)
        {
            Apple a = new Apple();
            a.chandi = "山东";
            Console.WriteLine(a.chandi); //山东
            Console.WriteLine(a.desc());  //水果类
            
            Dog an = new Dog();
            an.name = "dog";
            an.age();    //age is 1
            Console.WriteLine(an.name);  //dog

            Console.ReadKey();
        }
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值