Java抽象类(Abstract Class)与接口(Interface)区别

抽象类与接口比较

抽象类跟接口类似,都不能实例化,可能包含不需实现方法或已实现的方法。

抽象类可以定义一些不是静态或常量的字段,定义 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

posted @ 2018-04-19 20:51  海角在眼前  阅读(760)  评论(0编辑  收藏  举报