C# interface与abstract class区别

一、abstract class

abstract 声明抽象类抽象方法,一个类中有抽象方法,那么这个类就是抽象类了。所谓的抽象方法,就是不含主体(不提供实现方法),必须由继承者重写。因此,抽象类不可实例化,只能通过继承被子类重写。

实例代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ConsoleApplication1
{
    public abstract class Bus
    {
        public abstract void getName();
        public virtual void getTypes()
        {
            Console.WriteLine("bus");
        }
        public void getID()//一般方法,若在派生类中重写,须使用new关键字
        {
            Console.WriteLine("沪A 00000");
        }
    }
    public class car : Bus
    {
        public override void getName()
        {
            Console.WriteLine("奥迪");
        }
        public override void getTypes()
        {
            Console.WriteLine("car");
        }
    }
    class Program
    {
       
        static void Main(string[] args)
        {
            car mycar = new car();
            mycar.getName();
            mycar.getTypes();
            mycar.getID();
        }    
    }
}

输出:
奥迪
car
沪A 00000

二 interface

声明接口,只提供一些方法规约,不提供任何实现;不能用public、abstract等修饰,无字段、常量,无构造函数。

示例代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ConsoleApplication1
{
    public interface Bus
    {
        void getTypes();
    }
    public interface plane
    {
        void getfunc();
    }
    public class car : Bus,plane
    {
        
        public void getTypes()
        {
            Console.WriteLine("car");
        }
        public void getfunc()
        {
            Console.WriteLine("fly");
        }
    }
    class Program
    {
       
        static void Main(string[] args)
        {
            car mycar = new car();
            mycar.getTypes();
            mycar.getfunc();
        }    
    }
}

输出结果:
car
fly

三、区别

1.interface中不能有字段,而abstract class可以有;

2.interface中不能有public等修饰符,而abstract class 可以有。

3.interface 可以实现多继承

ΔΔΔ
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值