I study to the OCA 8 exam and I've noticed strange answer for Question 9 in Chapter 4 (answer on page 343, question on page 220). I think option C is incorrect. As you can see property numberWings has a getter called getNumWings . I am not an expert in JavaBeans conventions, but the book clearly states on page 206, table 4.5 that:
The method name must have a prefix of set/get/is, followed by the first letter of the property in uppercase, followed by the rest of the property name.
. In this example setter should be called getNumberWings to obey the convention. Am I right?
I am sorry if this topic was already mentioned on coderanch, but unfortunately I haven't been able to find it on the forum.
Lukasz Jarocki wrote:I think option C is incorrect.
You are wrong, option C is correct! But I definitely understand your confusion Let me try to clear your doubts.
In the JavaBeans specifications/convention there is no requirement between the property name and the instance variable you use to store the value for this property. So there could be a difference between the instance vaariable name and the property name (although in most cases both will mqtch). Take a look at this example:So the class JellyBean supports a property "color" and its value is stored in the instance variable ourColor and this is completely valid according to the JavaBeans specifications (in fact, this example is a simplified version from the JavaBeans specifications itself )
Back to the questions now:So the property is "numWings" and the value is stored in the instance variable numberWings. Because the property is "numWings", the setter method (if present) must be setNumWings; any other name would be invalid according to the JavaBeans specifications.
I haven't considered that. Usually people at work follow the rule that property name is the same as instance variable name (in fact Eclipse use this "rule" while auto-generating setters/getters). Good to know that it's not part of convention.
Lukasz Jarocki wrote:I haven't considered that. Usually people at work follow the rule that property name is the same as instance variable name (in fact Eclipse use this "rule" while auto-generating setters/getters). Good to know that it's not part of convention.
Thanks a lot.
It is indeed a convention (and a good one too) to have the same name for the variable as the property, if you are going to have a variable to store the property. Sometimes it is required to have a "property" in a class but not a corresponding variable. For example, if the property is a value generated by some computation. Unfortunately, the compiler cannot figure out whether you are using a variable to store the value of the property or you are computing the value on the fly. For this reason, it is legally valid to have an entirely different name for the variable. It is, however, a bad practice and should be avoided.