首页 > 其他 > 详细

Interface和abstract class

时间:2014-05-21 17:40:09      阅读:359      评论:0      收藏:0      [点我收藏+]

这两个概念在C#和Java类似,从语法上看

  1. Interface和abstract class都不能实例化。
  2. 可以继承多个Interface,但不能继承多个abstract class。
  3. 继承Interface的子类必须实现Interface全部的方法,而abstract class子类可以选择是否实现基类的方法。
  4. Interface除包含方法外,还可以包含属性,索引器,事件,不应该包含常量,构造函数,析构函数,静态成员。abstract class则可以包含上述任意成员。

从设计上看,Interface是定义继承的方法,而abstract class定义继承的对象。

  1. Interface表达HAS-A的关系

  2. abstract class表达IS-A的关系

How about an analogy: when I was in the Air Force, I went to pilot training and became a USAF pilot. At that point I wasn‘t qualified to fly anything, and had to attend aircraft type training. Once I qualified, I was a pilot (Abstract class) and a C-141 pilot (concrete class). At one of my assignments, I was given an additional duty: Safety Officer. Now I was still a pilot and a C-141 pilot, but I also performed Safety Officer duties (I implemented ISafetyOfficer, so to speak). A pilot wasn‘t required to be a safety officer, other people could have done it as well.

All USAF pilots have to follow certain Air Force-wide regulations, and all C-141 (or F-16, or T-38) pilots ‘are‘ USAF pilots. Anyone can be a safety officer. So, to summarize:

  • Pilot: abstract class
  • C-141 Pilot: concrete class
  • ISafety Officer: interface

added note: this was meant to be an analogy to help explain the concept, not a coding recommendation. See the various comments below, the discussion is interesting.  

reference:

http://kb.cnblogs.com/page/41836/

http://dev.yesky.com/436/7581936.shtml

http://stackoverflow.com/questions/761194/interface-vs-abstract-class-general-oo?lq=1 

http://stackoverflow.com/questions/56867/interface-vs-base-class

Interface和abstract class,布布扣,bubuko.com

Interface和abstract class

原文:http://www.cnblogs.com/sparkles/p/3740395.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!