What is the difference between an interface and abstract class?

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

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

30条回答
  •  清歌不尽
    2020-11-21 12:16

    I don't want to highlight the differences, which have been already said in many answers ( regarding public static final modifiers for variables in interface & support for protected, private methods in abstract classes)

    In simple terms, I would like to say:

    interface: To implement a contract by multiple unrelated objects

    abstract class: To implement the same or different behaviour among multiple related objects

    From the Oracle documentation

    Consider using abstract classes if :

    1. You want to share code among several closely related classes.
    2. You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
    3. You want to declare non-static or non-final fields.

    Consider using interfaces if :

    1. You expect that unrelated classes would implement your interface. For example,many unrelated objects can implement Serializable interface.
    2. You want to specify the behaviour of a particular data type, but not concerned about who implements its behaviour.
    3. You want to take advantage of multiple inheritance of type.

    abstract class establishes "is a" relation with concrete classes. interface provides "has a" capability for classes.

    If you are looking for Java as programming language, here are a few more updates:

    Java 8 has reduced the gap between interface and abstract classes to some extent by providing a default method feature. An interface does not have an implementation for a method is no longer valid now.

    Refer to this documentation page for more details.

    Have a look at this SE question for code examples to understand better.

    How should I have explained the difference between an Interface and an Abstract class?

提交回复
热议问题