On Chapter 2 on SCJP Study Guide by Kathy Sierra and Bert Bates, there's this Exam Watch (The topic is about inheritance):
Look out for code that appears to be asking about the behavior of a
method, when the problem is actually a lack of encapsulation. Look at the following
example, and see if you can figure out what’s going on:
Now consider this question: Is the value of right always going to be onethird
the value of left? It looks like it will, until you realize that users of the Foo class
don’t need to use the setLeft() method! They can simply go straight to the instance
variables and change them to any arbitrary int value.
Can anyone please expound on this matter? I mean will there questions like that? As far as java compiler is concerned, it is good. Thanks!
That's shows the lack of encapsulation......
the question is : " Is the value of right always going to be one third the value of left ?"
and answer is : NO
any object directly change the value of left and right, because that variables are public, and its not proper encapsulation means lack of encapsulation.
If you change the variable's modifier to "private" then the answer is : YES, and that's the proper encapsulation, every object has to access that setLeft() method to change the value of left and right.