首页 > 代码库 > Interface和abstract class
Interface和abstract class
这两个概念在C#和Java类似,从语法上看
- Interface和abstract class都不能实例化。
- 可以继承多个Interface,但不能继承多个abstract class。
- 继承Interface的子类必须实现Interface全部的方法,而abstract class子类可以选择是否实现基类的方法。
- 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