What is the difference between an interface and abstract class?

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

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

30条回答
  •  北恋
    北恋 (楼主)
    2020-11-21 12:22

    In short the differences are the following:

    Syntactical Differences Between Interface and Abstract Class:

    1. Methods and members of an abstract class can have any visibility. All methods of an interface must be public. //Does not hold true from Java 9 anymore
    2. A concrete child class of an Abstract Class must define all the abstract methods. An Abstract child class can have abstract methods. An interface extending another interface need not provide default implementation for methods inherited from the parent interface.
    3. A child class can only extend a single class. An interface can extend multiple interfaces. A class can implement multiple interfaces.
    4. A child class can define abstract methods with the same or less restrictive visibility, whereas class implementing an interface must define all interface methods as public.
    5. Abstract Classes can have constructors but not interfaces.
    6. Interfaces from Java 9 have private static methods.

    In Interfaces now:

    public static - supported
    public abstract - supported
    public default - supported
    private static - supported
    private abstract - compile error
    private default - compile error
    private - supported

提交回复
热议问题