Why should abstract class implement an interface?

It is a standard way of how OOP works. Imagine a class 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.

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. In such a case a Human could implement all of these interfaces, it would be perfectly fine.

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:

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

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.

Browse More Popular Posts

Leave a Comment