论坛首页 入门技术论坛

<Java.JavaEE面试整理>(9)--抽象类与接口有什么区别?以及如何选择?

浏览 1850 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-04-03  
"abstract class" or "interface"?

Q 12: 抽象类与接口有什么区别?以及如何选择? LF DP DC FAQ
A 12: In design, 我们想让基类只为其子类提供一个调用的接口,这样做我们并不想将此类实例化,我们只是在运行时将子类upcast to it(这样就可以获得多态特性了).我们可以用Java里的abstract关键字来将些基类定义为abstract class.
    Java里的Interface又将这个概念进一步地抽象了,利用它编译器将阻止对接口中展现的方法实现.这样我们就只能声明一个method而不能有任何的实现,而其实现类将提供相应方法的真正实现.这个Interface在OO设计中非常有用,利用它我们可以将接口与其具体的实现分开,并使以下几种优势成为可能:
    1,在无需硬性将一些毫不相干的类放入一个继承系统中的情况下,我们可以用此Interface将其包装.(Capture similarities among unrelated classes without artificially forcing a class relationship.)
    2,声明methods以让一个或多个类来实现.(Declare methods that one or more classes are expected to implement.)  
    3,只提供一个对象的接口,而将具体实现隐藏(Reveal an object's programming interface without revealing its actual implementation.)  
    4,可以在Java里实现多重接口的继承,利用这个多重接口继承我们像在其它OO语言里一样实现类的多重继承.(Model multiple interface inheritance in Java, which provides some of the benefits of full on multiple inheritances, a feature that some object-oriented languages support that allow a class to have more than one superclass.)
 
Q.那我们在什么情况下使用abstract class呢? When to use an abstract class?:
    当我们想获得继承里的实现继承时,这个abstact class是一个很好的选择.也就是说在Application framework里,我们可以在抽象类里定义那些default behavior,而将那些specific behavior交给子类去实现.Care should be taken not to overuse implementation inheritance as discussed in Q10 in Java section.
 
Q. Interface又适合什么样的设计情况呢?
    当想获得基于多态性的接口继承时,用interface,这样clients就只接触这个接口type而并不真正接触其具体实现.另一方面,若项目中的设计会经常改动时,就一定要使用Interface而别再使用抽象类.基于接口的编程可以大降低代码的耦合,其在代码重用方面的不足我们也可以通过对象的组合来获得.For example: The Spring framework’s dependency injection promotes code to an interface principle. Another justification for using interfaces  is that they solve the ‘diamond problem’ of traditional multiple inheritance.
 
Design pattern: Strategy design pattern lets you swap new algorithms and processes into your program without altering the objects that use them.
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics