What is the difference between an interface and abstract class?

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

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

30条回答
  •  鱼传尺愫
    2020-11-21 12:15

    An abstract class is a class whose object cannot be created or a class which cannot be instantiated. An abstract method makes a class abstract. An abstract class needs to be inherited in order to override the methods that are declared in the abstract class. No restriction on access specifiers. An abstract class can have constructor and other concrete(non abstarct methods ) methods in them but interface cannot have.

    An interface is a blueprint/template of methods.(eg. A house on a paper is given(interface house) and different architects will use their ideas to build it(the classes of architects implementing the house interface) . It is a collection of abstract methods , default methods , static methods , final variables and nested classes. All members will be either final or public , protected and private access specifiers are not allowed.No object creation is allowed. A class has to be made in order to use the implementing interface and also to override the abstract method declared in the interface. An interface is a good example of loose coupling(dynamic polymorphism/dynamic binding) An interface implements polymorphism and abstraction.It tells what to do but how to do is defined by the implementing class. For Eg. There's a car company and it wants that some features to be same for all the car it is manufacturing so for that the company would be making an interface vehicle which will have those features and different classes of car(like Maruti Suzkhi , Maruti 800) will override those features(functions).

    Why interface when we already have abstract class? Java supports only multilevel and hierarchal inheritance but with the help of interface we can implement multiple inheritance.

提交回复
热议问题