Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

to use procedures from a class, when is the best time to extend a class vs. create an instance of that class? [closed]

Tags:

java

In Java, I created a class CommonExcelFunctions to store procedures I use across a couple projects. there are no abstract procedures in the class. To use these, I'm trying to decide if I should make my other projects extend this class, or if I should instantiate it and access them all through the instantiated object. which way makes the most sense?

like image 617
Some Guy Tor78 Avatar asked Mar 18 '23 07:03

Some Guy Tor78


2 Answers

Never ever use inheritance just for the sake of code reuse. The subclass relationship should be a meaningful is-a relationship, especially in a language like Java where you have only single-inheritance.

For such utility functions you describe static would probably best. Otherwise, use composition, i.e. create a member.

like image 130
Janick Bernet Avatar answered Apr 27 '23 09:04

Janick Bernet


Similar to what @AlexisKing mentioned, I often will create a utility class (such as ExcelFunctionsUtil and create a bunch of static methods in there. This is nice when the code is to be reused in multiple places, but inheritance doesn't make sense. I think inheritance only makes sense if the sub-class could actually be considered an extension or child type of the parent class. For instance, if you created an UncommonExcelFunctions class, that would seem to be an appropriate child of CommonExcelFunctions, but an Accounting class would not make sense.

like image 38
mnd Avatar answered Apr 27 '23 10:04

mnd