zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    单例模式
    C++中迭代器原理、失效和简单实现
    C++中静态成员变量要在类外部再定义或初始化的原因
    idea maven javaweb项目迁移时的maven和版本报错问题解决(可解决同类错误)
    java 继承类之后,访问不到超类的属性的原因及解决方法
    spring boot admin
    javaweb 报表生成(pdf excel)所需要用到的技术和思路
    团队合作开发git冲突解决方案 Intellij IDEA
    【项目管理】 使用IntelliJ IDEA 将项目发布(提交)到GitLab
    IDEA/Git 设置多个push远程仓库或者同时提交多个push仓库
  • 原文地址:https://www.cnblogs.com/lovesong/p/8886206.html
Copyright © 2011-2022 走看看