What is the difference between an interface and abstract class?

前端 未结 30 1792
情歌与酒
情歌与酒 2020-11-21 11:51

What exactly is the difference between an interface and abstract class?

30条回答
  •  余生分开走
    2020-11-21 12:13

    The comparison of interface vs. abstract class is wrong. There should be two other comparisons instead: 1) interface vs. class and 2) abstract vs. final class.

    Interface vs Class

    Interface is a contract between two objects. E.g., I'm a Postman and you're a Package to deliver. I expect you to know your delivery address. When someone gives me a Package, it has to know its delivery address:

    interface Package {
      String address();
    }
    

    Class is a group of objects that obey the contract. E.g., I'm a box from "Box" group and I obey the contract required by the Postman. At the same time I obey other contracts:

    class Box implements Package, Property {
      @Override
      String address() {
        return "5th Street, New York, NY";
      }
      @Override
      Human owner() {
        // this method is part of another contract
      }
    }
    

    Abstract vs Final

    Abstract class is a group of incomplete objects. They can't be used, because they miss some parts. E.g., I'm an abstract GPS-aware box - I know how to check my position on the map:

    abstract class GpsBox implements Package {
      @Override
      public abstract String address();
      protected Coordinates whereAmI() {
        // connect to GPS and return my current position
      }
    }
    

    This class, if inherited/extended by another class, can be very useful. But by itself - it is useless, since it can't have objects. Abstract classes can be building elements of final classes.

    Final class is a group of complete objects, which can be used, but can't be modified. They know exactly how to work and what to do. E.g., I'm a Box that always goes to the address specified during its construction:

    final class DirectBox implements Package {
      private final String to;
      public DirectBox(String addr) {
        this.to = addr;
      }
      @Override
      public String address() {
        return this.to;
      }
    }
    

    In most languages, like Java or C++, it is possible to have just a class, neither abstract nor final. Such a class can be inherited and can be instantiated. I don't think this is strictly in line with object-oriented paradigm, though.

    Again, comparing interfaces with abstract classes is not correct.

提交回复
热议问题