Interfaces and Abstract classes confusion in Java with examples

后端 未结 7 938
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-25 13:55

I\'m having trouble understanding when to use an interface as opposed to an abstract class and vice versa. Also, I am confused when to extend an interface with another inter

7条回答
  •  眼角桃花
    2020-12-25 14:24

    This is a good question. There are many good and bad answers for this question. Typical question is, what is the difference between an abstract class an interface? Lets see where you use abstract classes and where you use interface.

    Where to use abstract classes: In terms of OOP, If there is an inheritance hierarchy then you should use an abstract class to model your design.
    enter image description here

    Where to use interfaces: When you have to connect different contracts(non related classes) using one common contract then you should use an interface. Lets take Collection framework as an example. enter image description here

    Queue,List,Set have different structures from their implementation.But still they share some common behaviors like add(),remove(). So we can create an interface called Collection and the we have declared common behaviors in the interface. As you see, ArrayList implements all the behaviors from both List and RandomAccess interfaces.Doing so we can easily add new contracts without changing the existing logic. This is called as "coding to an interface".

提交回复
热议问题