• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exam Watch SCJP Study Guide Book on Chapter 2

 
Yin Stadfield
Ranch Hand
Posts: 58
Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
Enkita mody
Ranch Hand
Posts: 333
Firefox Browser Java Windows XP
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Codes are correct over there but lack of encapsulation, what don't you understand in it ?
 
Ankit Gareta
Ranch Hand
Posts: 67
Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Yin,

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.

Hope that helps to solve your query.

Thanks,
Ankit
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic