What to prefer if Java Interface and Abstract class have abstract methods only?

Technical interview question is if an Interface and abstract class in java both contains only abstract methods then what would you choose or prefer between Interface and abstract class and why?

This is true that abstract class can have a method implemented into it, but, the restriction is that it also contains only abstract class. For example,




Interface will be the preference over abstract class if an abstract class contains only abstract methods.

Reason is that, when any derive or client class try to implement any interface then he is having a option of extending another class. But, if the derived class using abstract class, then it will not be able to extend another class as java does not support multiple inheritance using classes but interfaces.

You can read multiple inheritance example in java using interfaces and description about support of multiple inheritance using classes.

Second reason we can consider is that if we choose abstract class over interface as a software project design, then it may possible that after some time new software developer may implemented some methods in abstract class that will violet your design.

For example, he implements 2 classes and both contains a common method, say, read () method and inherits base class. As a good design, he may generalize 2 classes and can put read () method in abstract class. But, if he uses interface then he will not be able to do so.

For example. Below are two classes that contains common read () methods, so, they can be generalized and read() method can be moved to the abstract class.



To generalize delete the read() method form both class and move to abstract class e.g.


Read More