Supposing I was modeling a collection of projects. I suppose that I would have a two classes; one to represent the collection of Projects and a class for an individual Project. The collection of projects would have its properties and methods and a project would have its properties and methods. Now I think I know that there is a hashtable class. Can I base the Projects class as an extension of hashtable and would that be a sensible thing to do. The extended hashtable (class Projects) would contain the collection of Project objects. Does any of this make sense?
Percy Frankland wrote:
And can I create projectSet so that its an extension of HashSet so that it can have its own properties an methods in addition to those it would inherit?
Some points to ponder before extending any class which is not in direct control of your development.
1. Favor composition over inheritance,
2. Carefully override the methods and read the docs for the same.
Read #16 and #17 from "Effective Java", Joshua Bloch explain it beautifully.
1. Am I right that basing a new class on extending an existing one doesn't affect the original Class in any way?
1.5 Are there classes that you can't extend?
2. If I created a class myProjs (not extending anything) and it owned a container for my child objects, say cProjs then that seems clumsy. You have to refer to myProjs.cProjs.oChild to access a child object. Logically myProjs.cProjs is just a collection of oChild objects.
3. If you extend Hashtable to create myProjs then you can access a child object by myProjs.oChild. It removes a level of "nesting" that provides nothing. myProjs is independant of the original Class, except that it inherits all it's properties and methods. I then just have to add any extra methods and propeties I need to manage my myProj object.
4. If this approach is correct than wouldn't eveyone creating a class that represented a collection of objects base their collection class on an existing standard container class.
Rob is right, I should try it; I just wanted to check whether what I was planning to do was stupid.
Please don't update posts after they have been replied to. It changes the context of all posts after that, possibly making them no longer make sense.
But yes, your point 1) is very accurate. In this case, the object shouldn't be turned into a HashSet simply because it needs to be able to store data. It should contain a Set instead. If needed a few methods can be added to allow the editing of that Set - adding, removing, getting the size and iterating are the only ones that are usually needed.