CD mock exams, objective 3, OCP Exam 1, question 2
Answer D, "Woop has-a Hmpf and Woop has-a Zing" is not marked correct
- Woop has-a Hmpf: Woop is-a Zing and Zing has-a Hmpf, so this one should be true
- Woop has-a Zing: Woop is-a Zing, Zing has-a Hmpf and Hmpf has-a Zing, so this one should be also true
As much as I am aware, has-a is transitive, i.e. when A has-a B and B has-a C, then A has-a C
I have now checked and there has been already a debate about this on coderanch almost a decade ago
https://coderanch.com/t/252978/java-programmer-SCJP/certification/relation-transitive where the conclusion seemed to be not transitive
but see also e.g. K&B OCP JAVA 6 (310-065) Practice Exams book from 2010, practice exam I, question 54, where the correct answers assume has-a being transitive ("Jookers have Strings indirectly through Bostrons")
Before I'm adding this to the errata overview, I like to know what's the opinion of other ranchers about this topic.
Unlike the IS-A relationship, for me the HAS-A relationship is not transitive. Maybe the majority of the ranchers has a different opinion about this statement and I have to change mine. The reason why the HAS-A relationship is not transitive according to me can be illustrated very easily with this code snippet (using reflection)For me an Animal has one String (name), Lion has also one String (nickname) and CrazyZoo has a List of Animals (animals), but it doesn't have a String (nor a List of Strings).
And I think Java agrees with me (here's the reflection)Output:
Hope to get plenty of opinions about this topic!
PS. Reflection is not on the OCP exam, it was used for demonstration purposes only.
It's pretty clear to me that "has-a" is not transitive. I have a computer; a computer has a CPU. But I don't have a CPU... unless you get to throw in that weasel word "indirectly", which doesn't seem right to me. But you'd really have to go and find out how "composition" or "has-a" is defined for the purpose of the exam to determine whether you can throw in that "indirectly". After a bit of web-searching it seems to me that people writing about composition assume that you already know what they are talking about.
Paul Anilprem wrote:But a more relevant conundrum is the combination of is-a and has-a. If a super class has-a something, does the subclass also has-a that thing?
And does it make a difference if that something is public, protected, package-private or private?
For me the HAS-A relationship depends on the declared fields (and methods). So the Lion class HAS-A nickname but not a name. And it doesn't make a difference if name would have been protected or public. Although the Lion class would inherit the name field (if it was protected or public), it HAS-NOT-A name. It's the Animal class which HAS-A name and thus can decide to change name to name2, something which is not possible for the Lion class.