1. 程式人生 > >Java抽象類(Abstract Class)與接口(Interface)區別

Java抽象類(Abstract Class)與接口(Interface)區別

調用 con mean ast his pla 一個 tree 使用場景

抽象類與接口比較

抽象類跟接口類似,都不能實例化,可能包含不需實現方法或已實現的方法。

抽象類可以定義一些不是靜態或常量的字段,定義 public, protected, private訪問級別的具體方法。

接口的所有字段自動是public、靜態、常量,所有定義的方法的訪問級別都是public。

類只能繼承一個抽象類,可以實現多個接口。

抽象類使用場景

1、你想在幾個密切相關的類共享代碼。

2、你想讓繼承你抽象類的類有一些共用的字段或方法,或想設置protected, private的訪問級別。

3、你想聲明非靜態或非常量的字段。這樣可以定義訪問或修改字段狀態的方法。

接口使用場景

1、你想要不相關的類實現你的接口。

2、只想聲明特定數據類型的行為,不關註實現的情況。

3、實現多繼承效果。

例子

An example of an abstract class in the JDK is AbstractMap, which is part of the Collections Framework. Its subclasses (which include HashMap, TreeMap, and ConcurrentHashMap) share many methods (including get, put, isEmpty, containsKey, and containsValue) that AbstractMap defines.

An example of a class in the JDK that implements several interfaces is HashMap, which implements the interfaces Serializable, Cloneable, and Map<K, V>. By reading this list of interfaces, you can infer that an instance of HashMap (regardless of the developer or company who implemented the class) can be cloned, is serializable (which means that it can be converted into a byte stream; see the sectionSerializable Objects), and has the functionality of a map. In addition, the Map<K, V> interface has been enhanced with many default methods such as merge and forEach that older classes that have implemented this interface do not have to define.

Note that many software libraries use both abstract classes and interfaces; the HashMap class implements several interfaces and also extends the abstract class AbstractMap.

接口能不能有實現的方法?

Java8允許接口有默認方法和靜態方法,只不過調用方式不一樣,如下。

public interface RdNum {
    void play();
    
    static int getANum(){
        return 123;
    }
    
    default String getAStirng(String str){
        return str + "嚶嚶嚶";
    }
}

public class R implements Interface {
    ......
}

public class Test {
    public static void main(String[] args){
        R r = new R();
        System.out.println(r.getAStirng("哈哈哈"));    
        System.out.println(RdNum.getANum());
    } 
}

參考文獻

https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html

Java抽象類(Abstract Class)與接口(Interface)區別