zoukankan      html  css  js  c++  java
  • Java抽象类与接口的区别

    很多常见的面试题都会出诸如抽象类和接口有什么区别,什么情况下会使用抽象类和什么情况你会使用接口这样的问题。本文我们将仔细讨论这些话题。

    在讨论它们之间的不同点之前,我们先看看抽象类、接口各自的特性。

    抽象类

    抽象类是用来捕捉子类的通用特性的 。它不能被实例化,只能被用作子类的超类。抽象类是被用来创建继承层级里子类的模板。以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
    }
    复制代码

    当HttpServlet类继承GenericServlet时,它提供了service方法的实现:

    复制代码
    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
    }
    复制代码

    接口

    接口是抽象方法的集合。如果一个类实现了某个接口,那么它就继承了这个接口的抽象方法。这就像契约模式,如果实现了这个接口,那么就必须确保使用这些方法。接口只是一种形式,接口自身不能做任何事情。以Externalizable接口为例:

    public interface Externalizable extends Serializable {
     
        void writeExternal(ObjectOutput out) throws IOException;
     
        void readExternal(ObjectInput in) throws IOException, ClassNotFoundException;
    }

    当你实现这个接口时,你就需要实现上面的两个方法:

    复制代码
    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);
        }
    }
    复制代码

    抽象类和接口的对比

    什么时候使用抽象类和接口

    • 如果你拥有一些方法并且想让它们中的一些有默认实现,那么使用抽象类吧。
    • 如果你想实现多重继承,那么你必须使用接口。由于Java不支持多继承,子类不能够继承多个类,但可以实现多个接口。因此你就可以使用接口来解决它。
    • 如果基本功能在不断改变,那么就需要使用抽象类。如果不断改变基本功能并且使用接口,那么就需要改变所有实现了该接口的类。
  • 相关阅读:
    STM32 HAL库 CUBEMX 定时器双通道 高精度捕获PWM波
    STM32的CAN过滤器-bxCAN的过滤器的4种工作模式以及使用方法总结
    FreeRTOS — 消息队列
    STM32CubeMX 定时器配置时钟中的auto-reload preload
    使用TortoiseGit连接GitLab
    STM32CubeMx 定时器实现 微妙级延迟函数
    STM32 Keil新建工程报错“Loading PDSC Debug Description Failed for STMicroelectronics STM32Lxxxxxxx”
    STM32CubmeMx 串口IDLE中断+DMA读取不定长数据
    云龙51单片机视频教程全套包含案例课件及资料
    推荐一本很好的51单片机书籍,适合新手入门学习。
  • 原文地址:https://www.cnblogs.com/songhuiqiang/p/10647835.html
Copyright © 2011-2022 走看看