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
posted
0
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