Yevhen Ikonnykov wrote:Actually answers A and B look right, because you cannot call private fields outside the class. Am I right?
Yes private field are not directly accessible outside of the class but here private fields are not accessed outside of the class but in the main method which is in the class WaterBottle where they are declared.
The Study guide answer states:
D. Boolean fields initialize to false and references initialize to null, so empty is false and brand is null. Brand = null is output.
Explanation is correct but last statement regarding output is wrong.
I think It's typo actual output should be Empty = false, Brand = null
Hello Yevhen. It's great that you're preparing for the OCA exam. I passed mine recently and I would like to give you some tips that you may find helpful.
Verify code on your computer
In your post you said "Actually answers A and B look right". That's a valid concern that you have but what I would also do in your case is type this code into a file and compile it. You would see that the code compiles and then the next question would be why.
Making the code easier to read
I'd love to hear more questions from you and I just want to ask when you'll be posting code to use indentation and the Code formatting feature because it makes the code easier to read. For example, here's the code that you've posted but with indentation and the Code formatting feature:
Isn't that easier to read
Regarding the answer to your question
Ganesh answered your question but I just want to add something. This used to also confuse me, I used to think that a private instance field should only be accessible within the instance portion of the class (such as instance members and the constructors). However, as Ganesh pointed out, private instance fields are also accessible from static methods of the class, too. And what helped me to remember this is when I searched on google in what case this would be useful. An answer that I found was if you have a static factory method.
You may want to disallow client code from being able to instantiate your class using a constructor by making the constructor private and instead have a static factory method. You may want this if the creation of your class instances is complicated and you'd want a static factory method to take care of this. In this case you'd want your static factory method to have access to the private instance fields.
Here is an example of a class with a static factory method:
As you can see in the above example, it is very useful for a static method to have access to the private instance fields.
Let me know if this is helpful.
You'll never get away with this you overconfident blob! The most you will ever get is this tiny ad: