简体   繁体   English

为什么抽象类要实现接口?

[英]Why should abstract class implement an interface?

Since an abstract class can contain both complete and incomplete methods, when is it necessary to implement an interface?既然抽象类既可以包含完整的方法,也可以包含不完整的方法,那么什么时候需要实现接口呢? When should it implement an interface in an abstract class?什么时候应该在抽象类中实现接口?

It is a standard way of how OOP works.这是 OOP 工作的标准方式。 Imagine a class Human .想象一个类Human It is of course abstract as there can not be a concrete instance of a human.它当然是抽象的,因为不可能有一个人的具体实例。 A concrete implementation could for example be a class Person that requires a name and some other information.例如,一个具体的实现可以是一个需要名称和其他一些信息的类Person

public class Person extends Human {
    String name;
    int age;
}

A common usage of interfaces is to describe abilities .接口的一个常见用法是描述能力 In our example we could have interfaces like CanWalk , CanBreath , CanJump , NeedsWater , HasGender and so on.在我们的示例中,我们可以使用CanWalkCanBreathCanJumpNeedsWaterHasGender等接口。 In such a case a Human could implement all of these interfaces, it would be perfectly fine.在这种情况下, Human可以实现所有这些接口,这将是完美的。

public abstract class Human implements CanWalk,
    CanBreath, CanJump, NeedsWater, HasGender {
    ...
}

Those interfaces now have methods, like这些接口现在有方法,比如

public interface HasGender {
    String getGender();
}

and Human may implement them, but as an abstract human has no concrete gender, it may delegate the implementation to its implementing class Person :Human可以实现它们,但由于抽象的人类没有具体的性别,它可以将实现委托给它的实现类Person

public class Person extends Human {
    String name;
    int age;
    String gender;

    @Override
    public String getGender() {
        return gender;
    }
}

On the other hand there might be interfaces where Human can offer an implementation, like另一方面,可能存在Human可以提供实现的接口,例如

public interface NeedsWater {
    int amountOfWaterNeeded();
    void drink(int amount);
}

public abstract class Human implements CanWalk,
    CanBreath, CanJump, NeedsWater, HasGender {

    @Override
    public int amountOfWaterNeeded() {
        return 10;
    }
}

Finally we may have classes that work with interfaces.最后,我们可能有使用接口的类。 Like喜欢

public class WaterDistributor {
    public void distributeWaterTo(Iterable<NeedsWater> consumers) {
        for (NeedsWater c : consumers) {
            c.drink(c.amountOfWaterNeeded());
        }
    }
}

And you want to be able to pass your humans to that method, so you need to implement the interface.并且您希望能够将您的人员传递给该方法,因此您需要实现该接口。

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

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