简体   繁体   English

抽象类和非抽象超类

[英]abstract class and non abstract super class

If you have an abstract superclass named Car, and you have various subclasses of it, and abstract methods with no implementation, why bother with having an abstract class reference variable. 如果您有一个名为Car的抽象超类,并且它有各种子类,并且没有实现的抽象方法,那么为什么要麻烦一个抽象类引用变量呢? ie

Car myCar=new Honda(); 

In the Car class there are only abstract methods with no implementation so it would be useless to have right? 在Car类中,只有抽象方法没有实现,因此拥有对没有用吗?

It's not useless at all. 一点也不无用。 It allows you to write code that relies on the object being a Car without knowing anything about the specific type of Car . 它使您可以编写依赖于作为Car的对象的代码,而无需了解有关Car的特定类型的任何信息。

public abstract class Car {
    public abstract void tootHorn();
    public abstract void swerve();
    . . .
}

public class Driver {
    private Car car;
    public Driver(Car car) {
         this.car = car;
    }

    public void dealWithDanger() {
        car.tootHorn();
        car.swerve();
    }
    . . .
}

In the above code as posted, Car could just as easily have been an interface . 在上面发布的代码中, Car可以很容易地成为interface By making it a class, though, it is possible to implement some methods directly in the Car class that depends on the (as-yet unspecified) behavior of abstract methods that are specified by subclasses. 但是,通过将其设为一个类,有可能直接在Car类中实现某些方法,这些方法取决于子类指定的抽象方法的行为(迄今未指定)。

The key point of abstract classes is that you never have an instance of the abstract class itself; 抽象类的关键点是您永远不会拥有抽象类本身的实例。 code can only create instances of some concrete subclass. 代码只能创建某些具体子类的实例。 Nevertheless, lots of application logic can be written to be independent of the specific class of an object. 但是,可以编写许多独立于对象特定类的应用程序逻辑。

The abstract part prevents you from creating a car object like this: 抽象部分阻止您创建这样的汽车对象:

Car car = new Car();

It makes no sense to create just a car. 仅仅制造汽车是没有意义的。

看看这个: http : //docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html我认为这可以回答您的问题

Not really. 并不是的。 Car is an abstraction above Honda. 汽车是本田之上的抽象。 So that in the future, you can swap out Honda without worrying about massively modifying the code. 这样,将来您就可以替换本田而不必担心大规模修改代码。 In my case, I switched from a Honda Civic to a Subaru Outback as my family grew. 就我而言,随着家人的成长,我从本田思域转向斯巴鲁傲虎。 Guess what, I don't need to re-learn driving, because the "driving API" remains the same and I already know how to drive a Car. 猜猜是什么,我不需要重新学习驾驶,因为“驾驶API”保持不变,而且我已经知道如何驾驶汽车。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM