The moose likes Mock Exam Errata and the fly likes Question No.36 from Javacaps Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Professional Certification » Mock Exam Errata
Reply Bookmark "Question No.36 from Javacaps" Watch "Question No.36 from Javacaps" New topic
Author

Question No.36 from Javacaps

Yogini Soundalgekar
Greenhorn

Joined: Sep 29, 2000
Posts: 3
The question is
How can you implement encapsulation.
A) By making methods private and variable private
B) By making methods are public and variables as private
C) Make all variable are public and access them using methods
D) Making all methods and variables as protected.
I picked up A.But the given answer is B.
In java reference book I have read that a class is said to be fully encapsulated when all its methods & variables are private.
So I picked ans.A.
Can anybody please help me?
Thanks
Yogini
bill bozeman
Ranch Hand

Joined: Jun 30, 2000
Posts: 1070
If all the methods and variables are private, then the class wouldn't do anything because you couldn't access the methods or variables.
B is the correct answer because for encapsulation you want to have the variables private and then have methods that get and set those variables. Then if you were to change any variable name, or the way you are programming the class, you can just change the method body and no other code would be effected.
For example, if you have a variable named dog and it is public, if you later go back and say, that variable name doesn't make sense, a better name would be cat, any code that used this variable before you changed it would break because they all look at something called dog.
Now if you made it private and had a method named getDog that goes and gets the value of the variable dog, then if you changed the variable to cat all you need to do is change the method body to look at cat. All the other code using getDog will still work. That is encapsulation. Private variables and public methods.
Hope that helps,
Bill
Yogini Soundalgekar
Greenhorn

Joined: Sep 29, 2000
Posts: 3
That is a really good explanation.Thanks for it.
 
 
subject: Question No.36 from Javacaps
 
Threads others viewed
Access Modifiers
Mock exam question
Class
simple question on class variables accessability.
Encapsulation
developer file tools