I’m making a simple program that maintains a list of numbers, and I want this list to also have a name. Which is the best approach: have my list class extend ArrayList or have it include an ArrayList member? In both cases, there would of course be a “name” String member.
The first approach means I only have to implement a getter & setter for the name, but I think this would tie my class too closely to a particular implementation? For example, if I wanted to later use a Vector, than I would have to change code everywhere.
The second approach would make it easier to change the implementation, but of course becomes quite annoying for now, since I have to implement a bunch of wrappers.
I’ve read the SO posts regarding inheritance vs. composition, and since my list is a type of ArrayList, I am leaning towards the first approach. However, is there any differences to the discussion because I’m extending a Collection class vs extending a general class? Or am I over-thinking this?
Neither is better, its a trade-off as you mentioned.
If you do aggregation (has-a) you have to wrap all the functionality of the member you’re going to use (i.e implement functions that call them)
If you do inheritance, A lot of functions are added to your new class which might be unneccessary, And you need to implement abstract functions as well.
If you were in a C++ environment, private inheritance would be an option, But here both have pros and cons