Abstract Class versus Interface

引自:http://www.codeproject.com/KB/cs/abstractsvsinterfaces.aspx

By Rahman Mahmoodi | 7 Jan 2008
Abstract class versus Interface: Usage and Implementation.
  • Download source files - 8.75 KB

Introduction

In this article along with the demo project I will discuss Interfaces versus Abstract classes. The concept of Abstract classes and Interfaces is a bit confusing for beginners of Object Oriented programming. Therefore, I am trying to discuss the theoretical aspects of both the concepts and compare their usage. And finally I will demonstrate how to use them with C#.

Background

An Abstract class without any implementation just looks like an Interface; however there are lot of differences than similarities between an Abstract class and an Interface. Let's explain both concepts and compare their similarities and differences.

What is an Abstract Class?

An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.

What is an Interface?

An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn�t support multiple inheritance, interfaces are used to implement multiple inheritance.

Both Together

When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.

When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.

There are some similarities and differences between an interface and an abstract class that I have arranged in a table for easier comparison:

Feature

Interface

Abstract class

Multiple inheritance

A class may inherit several interfaces.

A class may inherit only one abstract class.

Default implementation

An interface cannot provide any code, just the signature.

An abstract class can provide complete, default code and/or just the details that have to be overridden.

Access Modfiers An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public An abstract class can contain access modifiers for the subs, functions, properties

Core VS Peripheral

Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface.

An abstract class defines the core identity of a class and there it is used for objects of the same type.

Homogeneity

If various implementations only share method signatures then it is better to use Interfaces.

If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.

Speed

Requires more time to find the actual method in the corresponding classes.

Fast

Adding functionality (Versioning)

If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.

If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.

Fields and Constants No fields can be defined in interfaces An abstract class can have fields and constrants defined

Using the Code

Let me explain the code to make it a bit easier. There is an Employee abstract class and an IEmployee interface. Within the Abstract class and the Interface entity I am commenting on the differences between the artifacts.

I am testing both the Abstract class and the Interface by implementing objects from them. From the Employee abstract class, we have inherited one object: Emp_Fulltime. Similarly from IEmployee we have inherited one object: Emp_Fulltime2.

In the test code under the GUI, I am creating instances of both Emp_Fulltime and Emp_Fulltime2 and then setting their attributes and finally calling the calculateWage method of the objects.

Abstract Class Employee

Collapse| Copy Code
 System; AbstractsANDInterfaces
{   Employee{  id;  lname;  fname;   ID{;;}   FirstName{;;}   LastName{;;}  Update(){  + id +  + lname +  + fname + ;}  Add(){  + id +  + lname +  + fname + ;}  Delete(){  + id +  + lname +  + fname + ;}  Search(){  + id +  + lname +  + fname + ;}   CalculateWage();}
}

Interface Employee

Collapse| Copy Code
 System; AbstractsANDInterfaces
{  IEmployee{ ID{;;} FirstName{;;} LastName{;;} Update(); Add(); Delete(); Search(); CalculateWage();}
}

Inherited Objects

Emp_Fulltime:

Collapse| Copy Code
 System; AbstractsANDInterfaces
{  Emp_Fulltime : Employee{ Emp_Fulltime(){}   ID{{ id;}{id = value;}}   FirstName{{ fname;}{fname = value;}}   LastName{{ lname;}{lname = value;}}   Add(){ .Add();}   Delete(){ .Delete();}   Search(){ .Search();}   Update(){ .Update();}   CalculateWage(){  + .fname +  + ;}}
}

Emp_Fulltime2:

Collapse| Copy Code
 System; AbstractsANDInterfaces
{  Emp_fulltime2 : IEmployee{  id;  lname;  fname; Emp_fulltime2(){}  ID{{ id;}{id = value;}}  FirstName{{ fname;}{fname = value;}}  LastName{{ lname;}{lname = value;}}  Add(){  + fname + ;}  Delete(){  + fname + ;}  Search(){  + fname + ;}  Update(){  + fname + ;}  CalculateWage(){  + fname +  + ;}}
}

Code for Testing

Collapse| Copy Code
  InterfaceExample_Click( sender, System.EventArgs e)
{{IEmployee emp;Emp_fulltime2 emp1 =  Emp_fulltime2();emp =  emp1;emp.ID = ;emp.FirstName=  ;emp.LastName =  ;MessageBox.Show(emp.Add().ToString());MessageBox.Show(emp.CalculateWage().ToString());}(Exception ex){MessageBox.Show(ex.Message);}}  cmdAbstractExample_Click( sender, System.EventArgs e)
{Employee emp;emp =  Emp_Fulltime();emp.ID = ;emp.FirstName=  ;emp.LastName =  ;MessageBox.Show(emp.Add().ToString());MessageBox.Show(emp.CalculateWage().ToString());}

Conclusion

In the above examples, I have explained the differences between an abstract class and an interface. I have also implemented a demo project which uses both abstract class and interface and shows the differences in their implementation.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

----------------------------------------------------------------------------------------------------------------------

引自:

http://en.csharp-online.net/Interfaces_and_Abstract_Classes

Summary

  • An Interface cannot implement methods.
  • An abstract class can implement methods.
  • An Interface can only inherit from another Interface.
  • An abstract class can inherit from a class and one or more interfaces.
  • An Interface cannot contain fields.
  • An abstract class can contain fields.
  • An Interface can contain property definitions.
  • An abstract class can implement a property.
  • An Interface cannot contain constructors or destructors.
  • An abstract class can contain constructors or destructors.
  • An Interface can be inherited from by structures.
  • An abstract class cannot be inherited from by structures.
  • An Interface can support multiple inheritance.
  • An abstract class cannot support multiple inheritance.

[转] Difference between Abstract classes and Interfaces相关推荐

  1. EffectiveJava(v3) - chapter3: Classes and Interfaces

    Classes and Interfaces 类和接口是Java编程中的核心, 提供了基础的抽象模块. 本章专注于如何使用类和接口来实现强壮的, 灵活的, 高可用的代码. Introduce Effe ...

  2. Python编程基础:第四十七节 抽象类Abstract Classes

    第四十七节 抽象类Abstract Classes 前言 实践 前言 抽象类可以这么理解,它就是一个模板,里面声明了子类必须定义的函数,但是对于每个函数都没有给出具体实现.所有函数的实现都是在子类中定 ...

  3. Fun with Unit Tests – Testing abstract classes

    Summary In this article I'll be looking into a trickier part of unit testing– testing the functional ...

  4. Java抽象类(Abstract Class)与接口(Interface)区别

    抽象类与接口比较 抽象类跟接口类似,都不能实例化,可能包含不需实现方法或已实现的方法. 抽象类可以定义一些不是静态或常量的字段,定义 public, protected, private访问级别的具体 ...

  5. 从JavaScript到TypeScript,Pt。 IIB:使用类,接口和混合器进行设计

    Class-based design has become such an instinct that many developers can't imagine any alternative. 基 ...

  6. JDK8 中抽象类和接口的区别

    英文原文:https://www.javacodegeeks.com/2014/04/abstract-class-versus-interface-in-the-jdk-8-era.html jdk ...

  7. java implement 泛型_csharplang.zh-cn

    ms.openlocfilehash ms.sourcegitcommit ms.translationtype ms.contentlocale ms.lasthandoff ms.locfilei ...

  8. 深度对比Jackson和Fastjson,最终我还是选择了...

    点击关注公众号,Java干货及时送达 来源:cnblogs.com/larva-zhh/p/11544317.html 为什么要替换fastjson 框架选型 替换fastjson Deseriali ...

  9. Design Pattern in Java[Challenge 2.1]

    尝试用简单的语言,讲述复杂的事情. 如发现文中的错误,或内容需要补充,忘不吝指教! CHALLENGE 2.1 Write down three differences between abstrac ...

最新文章

  1. 【机器学习基本理论】详解最大后验概率估计(MAP)的理解
  2. (最新最全)windows使用anaconda安装pytorch进行深度学习并使用GPU加速
  3. 唐筛的准确率这么低为什么还要做_做注塑这么苦,为什么你还要坚持?
  4. 超过3000赞的「机器学习路线图」,教你升级打怪全攻略
  5. python爬虫之多线程、多进程+代码示例
  6. CNN经典模型:GoogLeNet(从Inception v1到v4的演进)
  7. Err.number错误号和错误说明(一)
  8. Python中出现问题:ValueError: not enough values to unpack (expected x, got x)的可能汇总及解决办法
  9. 《筑墙——只需一点点安全常识就能阻止网络犯罪》
  10. swper 实现滑动切换功能的两种方式
  11. 【Python】可视化科学计算笔记
  12. Java中的RSA加解密工具类:RSAUtils
  13. 物联网大数据平台功能有哪些
  14. Windows 工具栏ToolBar
  15. Ad-hoc Testing(随机测试)
  16. 计算机职业素质测评报告,人员素质测评报告书.doc
  17. Linux命令(七)——网络配置和网络通信
  18. Qt虚拟键盘相关内容
  19. 讯捷FW150US Ubuntu 13.04 驱动
  20. 控制系统中开环传递函数表征闭环特性

热门文章

  1. 牵手大众、现代,滴滴绯闻“女友”Aurora无人车启动商业化
  2. django文件——django + jquery-file-upload上传篇(二)-- 插件实现文件上传+进度条显示 +拖入文件上传...
  3. mongodb可视化工具robo3T的安装和使用
  4. ssh全屏退出的办法
  5. Android学习笔记(十五)——实战:强制下线
  6. SQL查询集合合并成字符串
  7. 通过文件锁 Lockfile/flock 让脚本单实例运行
  8. MongoDB数据库(二):增删查改
  9. 20180921 su与sudo命令、限制root用户通过ssh远程登录
  10. CFFI - 简介及简单使用