I had an interview today where, yet again, I got asked the difference between an abstract class and an interface. In fact, I would estimate about 50% of the job interviews I've had for Java development have asked this exact question.
The answer is pretty straight forward. An interface defines some behaviour that can be added to an existing class. The class can choose how to implement that behaviour, but by implementing the interface, they are saying that they have some capability.
And abstract class isn't used to add capabilities to an existing class. Instead, it's meant to be a basis for future classes. Abstract classes can also do some things that interfaces can't, specifically have state and default method implementations.
If you have a job interview for a Java developer position, I recommend that you know how to answer this question.
I agree with the above answer. One more thing you can add is that interface has fully implementation of abstract since by default it is public abstract only but abstract class is partially implementation of abstract. Second one is if you want to work in object Action not in properties then you might choose interface but if you want to work with action as well as properties then you have the option abstract class.
ReplyDelete