zoukankan      html  css  js  c++  java
  • Abstract Methods and Classes

    阅读了Java的官方Doc,在此总结如下。

    Abstract Class & Method

    In jave, "abstract" can be a modifier to class and method.

    Abstract class:

    A class that is declared abstract—it may or may not include abstract methods.

    Abstract classes cannot be instantiated, but they can be subclassed.

    Abstract method:

    a method that is declared without an implementation (without braces, and followed by a semicolon), like this:

    abstract void moveTo(double deltaX, double deltaY);

    Relationship:

    If a class includes abstract methods, then the class itself must be declared abstract.

    If subclass of an abstract class does not implement all of the abstract methods, then the subclass must also be declared abstract.

    Abstract Class vs Interface

    Same:

    Cannot be inistantiated.

    Difference:

    1. With abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods.

    With interfaces, all fields are automatically public, static, and final, and all methods that you declare or define (as default methods) are public.

    2. You can extend only one class, whether or not it is abstract, whereas you can implement any number of interfaces.

    3. A class that implements an interface must implement all of the interface's methods.

    When to use Abstract Class:

    1. You want to share code among several closely related classes.
    2. You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
    3. You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.

    When to use Interface:

    1. You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.
    2. You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
    3. You want to take advantage of multiple inheritance of type.

  • 相关阅读:
    机器学习中的正则化问题(2)——理解正则化
    详解 Python 中的下划线命名规则
    编程面试的算法概念汇总
    group by多字段查询解决礼物统计
    一分钟学会Spring Boot多环境配置切换
    Maven 多模块父子工程 (含Spring Boot示例)
    第1章 Spring Cloud 构建微服务架构(一)服务注册与发现
    第3章 Spring Boot 入门指南
    第5章 Spring Boot 功能
    第4章 CentOS软件安装
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4949574.html
Copyright © 2011-2022 走看看