Relationships between Java classes - inheritance, packaging and others
Archive - Originally posted on "The Horse's Mouth" - 2010-07-10 18:05:15 - Graham Ellis
When you're designing classes in Java, you need to consider their relationship with one another in various ways.
• You need to consider class INHERITANCE - which classes are based on which other classes. For example, a Pet could be based on (i.e. extended from) an Animal.
• You need to consider which INTERFACES your class implements - for that lets you define commonly named methods across a series of classes, and call those classes with the same code, even if they don't use inheritance.
• You need to consider which other classes objects in you class CONTAIN. For example, a Pet object will contain an address object, to hold information about where the pet lives.
• And you may wish to PACKAGE your classes - group them together under a name / named directory so that you can distibute them and handle them as a unit, and so that you can give them more permissions within the group than they would have outside.
Although there are similarities between these relationships, I wouldn't go so far as to sat they're the same, and indeed you need to consider all of them in your design.
On our recent Java Bootcamp Course, I wrote a new complete example of package. There's a "control" example - all in the one class - at Geraldine.java. I then took the object code and put it into a class called Isobel in a package called gowdie. See Isobel.java for that code, and if you want to see how it's called, there are examples in Hattie.java where we're specifying gowdie.Isobel in full every time we refer to it, and in Hilda.java. These new examples all include much more extensive comments - please follow the links if you want to read more programming detail, and to see sample output
Footnote ... in case you wonder about the "gowdie.Isobel" class name ... on last week's course, we used names of ladies for classes, then we added famous surnames for associated data. A bit 'silly' / a bit of fun, if you like, and not recommended for production code. But by going through the alphabet, delegates can look back in the future and see the order of the examples just by going up the alphabet.
It turns out that "Isobel" with an "O" is a slightly unusual Scottish spelling of "Isabel" with an "A", and the most famous Isobel was Isobel Gowdie, a Scottish Witch. News to me - I'm not into that sort of thing, but seeing as the class was all about animals, it looks appropriate. Apparently, our Isobel Gowdie claimed that she could take on animal form ...