Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Java 接口與抽象類的差別,一次講透

1. 概述

一套軟體設計好不好,很大程度上取決於整體架構,而整體架構其實就是你對宏觀商業業務的抽象框架。當代表業務邏輯的高層抽象層結構合理時,底層實作要思考的就只剩演算法與具體業務細節了;日後要開發相近專案時,抽象層甚至可以直接復用。物件導向設計的復用重點,應該是抽象層的復用,而不是某個程式碼區塊的復用。

談到抽象,就繞不開曾讓很多人頭痛的 Java 接口與 Java 抽象類。

既然物件導向設計重在抽象,接口與抽象類的存在就是必然的。它們代表抽象型別,也就是我們要提出的抽象層的具體形式。要提高程式的復用率、可維護性與可擴展性,就必須面向接口、面向抽象編程,正確地把接口與抽象類放在結構層次的頂端。

兩者相似之處很多,差異也很關鍵,比較一下就能看出各自的最佳位置。

  1. 最大的差別在於:抽象類可以提供部分方法的實作,接口不行(interface 中只能定義方法,不能有實作;abstract class 則可以同時有具體方法與抽象方法)。這大概是抽象類唯一的優點,但非常有用。往抽象類加入一個新的具體方法時,所有子類立刻都擁有了它;而往接口加入新方法,所有實作該接口的類都會編譯失敗,每個類都得補上實作。這正是新舊 mapreduce API 差異的類似問題——新 API 更傾向抽象類而非接口,因為更容易擴展。
  2. 抽象類的實作只能由其子類給出,也就是說實作必須落在該繼承等級結構之內。加上 Java 是單繼承,抽象類作為型別定義工具的效能大打折扣。接口在這點上優勢明顯:任何實作了接口方法的類都具備該接口型別,而一個類可以實作任意多個接口,因而擁有多種類型。(接口與抽象類都可以定義型別,但只能用具體實作類來建立實例。)
  3. 由此可見,接口是定義混合型別的理想工具——混合型別表示一個類除了主型別的行為,還具備其他次要行為。
  4. 結合上述優勢,就得到一個經典設計模式:宣告型別的工作交給接口,同時提供一個實作了該接口的抽象類,其他屬於此型別的具體類則可自由選擇實作接口或繼承抽象類。也就是說在層次結構中,接口在最上面,抽象類緊隨其後,兩者的優點都發揮到極致。這就是「缺省適配模式」。Java 標準 API 大量使用這種模式,並遵循固定命名規範:Abstract + 接口名。(A extends AbstractB implements interfaceC,則 A 可以選擇是否 @Override 接口與抽象類中的方法。)

接口與抽象類的存在,是為了供具體類實作與繼承。如果你打算寫一個具體類去繼承另一個具體類,那設計大概出了問題。抽象類天生為繼承而存在,它的抽象方法就是為了強制子類必須實作。

此外,變數型別宣告、參數型別宣告、方法回傳型別說明與型別轉換,都應該用接口或抽象類,而不是具體類。

2. 實例

下面是一個具體的接口 Action:

package org.springframework.webflow.execution;
public interface Action {
    public Event execute(RequestContext context) throws Exception;
} 

接口中定義了一個沒有實作的方法 execute(),回傳型別為 Event。這些方法的實作由 implements 這個接口的類提供。

再看一個實作 Action 的抽象類 AbstractAction:

package org.springframework.webflow.action;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.ClassUtils;
import org.springframework.webflow.core.collection.AttributeMap;
import org.springframework.webflow.execution.Action;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;

public abstract class AbstractAction implements Action, InitializingBean {
    protected final Log logger = LogFactory.getLog(getClass());
    public EventFactorySupport getEventFactorySupport() {
        return new EventFactorySupport();
    }
    public void afterPropertiesSet() throws Exception {
        try {
            initAction();
        } catch (Exception ex) {
            throw new BeanInitializationException("Initialization of this Action failed: " + ex.getMessage(), ex);
        }
    }
    protected void initAction() throws Exception {
    }
    protected Event success() { return getEventFactorySupport().success(this); }
    protected Event success(Object result) { return getEventFactorySupport().success(this, result); }
    protected Event error() { return getEventFactorySupport().error(this); }
    protected Event error(Exception e) { return getEventFactorySupport().error(this, e); }
    protected Event yes() { return getEventFactorySupport().yes(this); }
    protected Event no() { return getEventFactorySupport().no(this); }
    protected Event result(boolean booleanResult) { return getEventFactorySupport().event(this, booleanResult); }
    protected Event result(String eventId) { return getEventFactorySupport().event(this, eventId); }
    protected Event result(String eventId, AttributeMap resultAttributes) { return getEventFactorySupport().event(this, eventId, resultAttributes); }
    protected Event result(String eventId, String resultAttributeName, Object resultAttributeValue) { return getEventFactorySupport().event(this, eventId, resultAttributeName, resultAttributeValue); }

    public final Event execute(RequestContext context) throws Exception {
        Event result = doPreExecute(context);
        if (result == null) {
            result = doExecute(context);
            doPostExecute(context);
        } else {
            if (logger.isInfoEnabled()) {
                logger.info("Action execution disallowed; pre-execution result is '" + result.getId() + "'");
            }
        }
        return result;
    }
    protected String getActionNameForLogging() { return ClassUtils.getShortName(getClass()); }
    protected Event doPreExecute(RequestContext context) throws Exception { return null; }
    //抽象方法
    protected abstract Event doExecute(RequestContext context) throws Exception;
    protected void doPostExecute(RequestContext context) throws Exception {
    }
} 

在 AbstractAction 中,同時存在具體實作的方法與沒有實作的抽象方法:

//抽象方法
protected abstract Event doExecute(RequestContext context) throws Exception; 

要留意的是:抽象類中若某方法沒有實作(方法後面沒有 {}),必須加上 abstract 宣告;而接口中不需要寫 abstract。抽象類之所以被稱為抽象類,正是因為它含有抽象方法。

Copyright © Linux教程網 All Rights Reserved