Interfaces and Abstract classes confusion in Java with examples

后端 未结 7 946
佛祖请我去吃肉
佛祖请我去吃肉 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:32

    This is question that will come to when designing class hierarchies that are bit complicated that normal. But generally there are few things you need to know when using abstract classes and interfaces

    Abstract Class

    • Allows you to leverage the power of using constructors and constructor overriding
    • Restrict the class having multiple inheritance(This is particularly useful if you are designing a complicated API)
    • Instance variables and method implementations
    • Leverage the power of method super calling(Use super to call the parent abstract class's implementation)

    Interface

    • Enables multiple inheritance - you can implement n number of interfaces
    • Allows to represent only conceptual methods (No method bodies)

    Generally use Interfaces for '-able' clause(as in functionality). Eg:-

    1. Runnable
    2. Observable

    Use abstract classes for something like is-a(evolution format). Eg:-

    1. Number
    2. Graphics

    But hard and fast rules are not easy to create. Hope this helps

提交回复
热议问题