When to implement an interface and when to extend a superclass?

后端 未结 11 865
遇见更好的自我
遇见更好的自我 2020-11-30 04:41

I\'ve been reading a lot about interfaces and class inheritance in Java, and I know how to do both and I think I have a good feel for both. But it seems that nobody ever rea

11条回答
  •  被撕碎了的回忆
    2020-11-30 05:21

    The main reason for using abstract classes and interfaces are different.

    An abstract class should be used when you have classes that have identical implementations for a bunch of methods, but vary in a few.

    This may be a bad example, but the most obvious use of abstract classes in the Java framework is within the java.io classes. OutputStream is just a stream of bytes. Where that stream goes to depends entirely on which subclass of OutputStream you're using... FileOutputStream, PipedOutputStream, the output stream created from a java.net.Socket's getOutputStream method...

    Note: java.io also uses the Decorator pattern to wrap streams in other streams/readers/writers.

    An interface should be used when you just want to guarantee that a class implements a set of methods, but you don't care how.

    The most obvious use of interfaces is within the Collections framework.

    I don't care how a List adds/removes elements, so long as I can call add(something) and get(0) to put and get elements. It may use an array (ArrayList, CopyOnWriteArrayList), linked list (LinkedList), etc...

    The other advantage in using interfaces is that a class may implement more than one. LinkedList is an implementation of both List and Deque.

提交回复
热议问题