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

本文探讨了抽象类与接口在Java中的区别,并讨论了在不同场景下如何选择使用抽象类或接口。接口允许实现多态性和接口继承,适用于需要分离接口和实现的设计;而抽象类则适用于希望提供部分默认行为,留给子类定制特定行为的情况。
"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.
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值