What is the difference between an interface and abstract class?

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

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

30条回答
  •  再見小時候
    2020-11-21 12:21

    The shortest way to sum it up is that an interface is:

    1. Fully abstract, apart from default and static methods; while it has definitions (method signatures + implementations) for default and static methods, it only has declarations (method signatures) for other methods.
    2. Subject to laxer rules than classes (a class can implement multiple interfaces, and an interface can inherit from multiple interfaces). All variables are implicitly constant, whether specified as public static final or not. All members are implicitly public, whether specified as such or not.
    3. Generally used as a guarantee that the implementing class will have the specified features and/or be compatible with any other class which implements the same interface.

    Meanwhile, an abstract class is:

    1. Anywhere from fully abstract to fully implemented, with a tendency to have one or more abstract methods. Can contain both declarations and definitions, with declarations marked as abstract.
    2. A full-fledged class, and subject to the rules that govern other classes (can only inherit from one class), on the condition that it cannot be instantiated (because there's no guarantee that it's fully implemented). Can have non-constant member variables. Can implement member access control, restricting members as protected, private, or private package (unspecified).
    3. Generally used either to provide as much of the implementation as can be shared by multiple subclasses, or to provide as much of the implementation as the programmer is able to supply.

    Or, if we want to boil it all down to a single sentence: An interface is what the implementing class has, but an abstract class is what the subclass is.

提交回复
热议问题