Difference between abstract class with all method abstract and interface?

后端 未结 7 1844
感动是毒
感动是毒 2020-12-29 14:05

I had an interview where interviewer asked me first what is the difference between abstract class with all the methods abstract and an interface.

I replied that if

7条回答
  •  北荒
    北荒 (楼主)
    2020-12-29 14:19

    Here are the differences:

    1. A class can extend exactly abstract class, but can implement any number of interfaces.
    2. An abstract class can have protected, private (does not apply to your question), package, and public methods, but an interface can only have public methods.
    3. An abstract class can have instance variables (often called data members or properties) while an interface can only have static variables.

    The answer to the question: "blah never extend blah implement contract blah" is this: "I would use an abstract class if I did needed instance variables and/or non-public methods and otherwise I would use an interface".

提交回复
热议问题