What is the difference between an interface and abstract class?

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

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

30条回答
  •  -上瘾入骨i
    2020-11-21 12:12

    It's pretty simple actually.

    You can think of an interface as a class which is only allowed to have abstract methods and nothing else.

    So an interface can only "declare" and not define the behavior you want the class to have.

    An abstract class allows you to do both declare (using abstract methods) as well as define (using full method implementations) the behavior you want the class to have.

    And a regular class only allows you to define, not declare, the behavior/actions you want the class to have.

    One last thing,

    In Java, you can implement multiple interfaces, but you can only extend one (Abstract Class or Class)...

    This means inheritance of defined behavior is restricted to only allow one per class... ie if you wanted a class that encapsulated behavior from Classes A,B&C you would need to do the following: Class A extends B, Class C extends A .. its a bit of a round about way to have multiple inheritance...

    Interfaces on the other hand, you could simply do: interface C implements A, B

    So in effect Java supports multiple inheritance only in "declared behavior" ie interfaces, and only single inheritance with defined behavior.. unless you do the round about way I described...

    Hopefully that makes sense.

提交回复
热议问题