Java抽象類(lèi)與接口區(qū)別詳解
很多常見(jiàn)的面試題都會(huì)出諸如抽象類(lèi)和接口有什么區(qū)別,什么情況下會(huì)使用抽象類(lèi)和什么情況你會(huì)使用接口這樣的問(wèn)題。本文我們將仔細(xì)討論這些話(huà)題。
在討論它們之間的不同點(diǎn)之前,我們先看看抽象類(lèi)、接口各自的特性。
抽象類(lèi)
抽象類(lèi)是用來(lái)捕捉子類(lèi)的通用特性的 。它不能被實(shí)例化,只能被用作子類(lèi)的超類(lèi)。抽象類(lèi)是被用來(lái)創(chuàng)建繼承層級(jí)里子類(lèi)的模板。以JDK中的GenericServlet為例:
public abstract class GenericServlet implements Servlet, ServletConfig, Serializable { // abstract method abstract void service(ServletRequest req, ServletResponse res); void init() { // Its implementation } // other method related to Servlet}
當(dāng)HttpServlet類(lèi)繼承GenericServlet時(shí),它提供了service方法的實(shí)現(xiàn):
public class HttpServlet extends GenericServlet { void service(ServletRequest req, ServletResponse res) { // implementation } protected void doGet(HttpServletRequest req, HttpServletResponse resp) { // Implementation } protected void doPost(HttpServletRequest req, HttpServletResponse resp) { // Implementation } // some other methods related to HttpServlet}
接口
接口是抽象方法的集合。如果一個(gè)類(lèi)實(shí)現(xiàn)了某個(gè)接口,那么它就繼承了這個(gè)接口的抽象方法。這就像契約模式,如果實(shí)現(xiàn)了這個(gè)接口,那么就必須確保使用這些方法。接口只是一種形式,接口自身不能做任何事情。以Externalizable接口為例:
public interface Externalizable extends Serializable { void writeExternal(ObjectOutput out) throws IOException; void readExternal(ObjectInput in) throws IOException, ClassNotFoundException;}
當(dāng)你實(shí)現(xiàn)這個(gè)接口時(shí),你就需要實(shí)現(xiàn)上面的兩個(gè)方法:
public class Employee implements Externalizable { int employeeId; String employeeName; @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { employeeId = in.readInt(); employeeName = (String) in.readObject(); } @Override public void writeExternal(ObjectOutput out) throws IOException { out.writeInt(employeeId); out.writeObject(employeeName); }}
抽象類(lèi)和接口的對(duì)比
什么時(shí)候使用抽象類(lèi)和接口
如果你擁有一些方法并且想讓它們中的一些有默認(rèn)實(shí)現(xiàn),那么使用抽象類(lèi)吧。 如果你想實(shí)現(xiàn)多重繼承,那么你必須使用接口。由于Java不支持多繼承,子類(lèi)不能夠繼承多個(gè)類(lèi),但可以實(shí)現(xiàn)多個(gè)接口。因此你就可以使用接口來(lái)解決它。 如果基本功能在不斷改變,那么就需要使用抽象類(lèi)。如果不斷改變基本功能并且使用接口,那么就需要改變所有實(shí)現(xiàn)了該接口的類(lèi)。以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. python實(shí)現(xiàn)讀取類(lèi)別頻數(shù)數(shù)據(jù)畫(huà)水平條形圖案例2. python中PyQuery庫(kù)用法分享3. python操作數(shù)據(jù)庫(kù)獲取結(jié)果之fetchone和fetchall的區(qū)別說(shuō)明4. JSP動(dòng)態(tài)實(shí)現(xiàn)web網(wǎng)頁(yè)登陸和注冊(cè)功能5. Ajax實(shí)現(xiàn)頁(yè)面無(wú)刷新留言效果6. php使用正則驗(yàn)證密碼字段的復(fù)雜強(qiáng)度原理詳細(xì)講解 原創(chuàng)7. CSS3實(shí)現(xiàn)動(dòng)態(tài)翻牌效果 仿百度貼吧3D翻牌一次動(dòng)畫(huà)特效8. PHP獲取時(shí)間戳等相關(guān)函數(shù)匯總9. php5.6不能擴(kuò)展redis.so的解決方法10. AJAX實(shí)現(xiàn)數(shù)據(jù)的增刪改查操作詳解【java后臺(tái)】
