Jeanne Boyarsky wrote:Charlie,
For future questions, can you post more specifically where they are from. In particular,t he practice exam number (1, 2 or 3) or the chapter #/question #. For example, this question is from the online practice exam 3. (I have to open four files to find the question without this information. And since you already know where it came from...)
charlie swift wrote:I'm really sorry about that. In future, I'll keep that in mind and add question# and test# so that it is easier to identify it.
Campbell Ritchie wrote:Surely it would be a copy of the honey instance variable that you are returning? Remember that Java® is case‑sensitive.
But the Honey class does appear to be mutable, having an add() method. That means, in order to get complete encapsulation, one should take a defensive copy of the instance of Honey whenever it is passed to the constructor or a setXXX method, or when it is returned from a getXXX method.
Campbell Ritchie wrote:No. It would be better to return a copy of the Honey object if you want to be fully encapsulated. Also consider the setHoney method. That allows you to change the honey content of the jar for another honey object. Consider whether that breaches encapsulation. Search the Beginning forum and Java in General for set methods encapsulation and you will probably find more discussion there. Try this thread and this one. Does removing all the honey from a jar and replacing it with different honey reflect what happens in real life? Can you add constraints to the setHoney method to restrict the permissible size or sugar content of the honey? Can you implement a Honey class which doesn't have weight and sugarPercentage fields? Maybe it has waterWeight and sugarWeight fields instead, since honey comprises sugar and water (just about)? Can you implement the getHoneyPercentage method like this?These are all possibilities you should consider if you restrict access to the fields.