为什么首先有抽象 类 ?

Why are there abstract classes in the first place?

我知道创建抽象 class 背后的概念性用途,即为其子class 定义一个公共接口,其中一些实现留给单独的子classes.

我的假设是否正确,即技术上不需要抽象 classes,因为您无论如何都可以覆盖 superclass 方法?创建抽象 classes 只是为了让开发人员更清楚 classes 的意图吗?

我的意思的例子:

// Using an abstract class
abstract class Car
{
    int fuel;

    int getFuel()
    {
         return this.fuel;
    }

    abstract String getColor();
}

class RedCar extends Car
{
    String getColor()
    {
        return "red";
    }
}


// Without an abstract class
class Car
{
    int fuel;

    int getFuel()
    {
         return this.fuel;
    }

    String getColor()
    {
         return "defaultColor";
    }

class RedCar extends Car
{
    String getColor()
    {
        return "red";
    }
}

Were abstract classes just created to make the intention of the classes clearer to the developer?

没错,但它也会阻止开发人员做 "silly" 事情。

例如,您不能创建抽象 classes 的实例。在您的代码上下文中,创建 "general" Car 没有意义。您只能创建 BlueCarRedCar 或其他子 class。虽然 anonymous subclass 的实例可能看起来像抽象 classes 的实例,但它们最终是由 subclasses 构造的。但是,如果将 Car class 抽象化,开发人员将不会意外创建 Car 的实例,因为编译器会报错。

Abstract classes 还强制开发人员实现抽象方法。有了你的非抽象 Car class,我可以继承它而忘记我需要覆盖 getColor。现在代码的某些其他部分可能会调用 getColor 并获得无意义的结果 "defaultcolor"。默认颜色是什么鬼?使方法抽象化会迫使子classes 考虑实现所需的方法。

我认识的大多数人都避免抽象 classes。从应用程序程序员的角度来看,我的意见 应该避免抽象 classes。使用界面更加灵活,不会强迫您的工作遵守 class 层次结构。

有点正式:抽象class是严格的继承,而接口是组合

抽象 classes 有用的一个例子是制作 class 库。 abstract classes 强制执行的层次结构可以使应用程序程序员更容易理解该库。但是,我确实相信这是以库的更长开发时间为代价的。