Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case for using inheritance or interface in Java?

Tags:

java

I have a very simple application which needs a data source. At present it is a flat file but later on it will change to a database. I need your opinion on using inheritance or interfaces here. Which one would be better and why? My opinion is using interfaces because it would be flexible but then i could make data source as an abstract class too.

like image 436
Phoenix Avatar asked Jul 16 '12 16:07

Phoenix


2 Answers

You would use an abstract class where there is common functionality that all the implementations need access to. Here the database and file implementations are so different they will have nothing in common, so I'd go with interfaces.

like image 67
Nathan Hughes Avatar answered Sep 29 '22 17:09

Nathan Hughes


You use an interface when only the methods and types for accessing the data will remain the same. You use inheritance when there will be common code/functionality between things that needs to be shared as well.

In this case, it would seem an interface would suffice and utilizing an abstract class with no common code would be a waste. One often forgotten benefit of using interfaces is that you can implement multiple interfaces at once whereas you can only inherit from one parent class.

like image 35
Daniel DiPaolo Avatar answered Sep 29 '22 19:09

Daniel DiPaolo