Confused with Java Encapsulation Concept -


good day!

i reading java book encapsulation , mentioned getter , setter method.

i've read hide attributes, must mark instance variables "private" , make "public" method of getter , setter access data. tried making similar not conventional code follows:

public class addressbookentry {      private string name;     private string address;     private string telno;     private string email;      public void getallinfo() {         name = joptionpane.showinputdialog("enter name: ");         address = joptionpane.showinputdialog("enter address: ");         telno = joptionpane.showinputdialog("enter tel. no: ");         email = joptionpane.showinputdialog("enter email address: ");     } } 

does code above exposes variables because assigned directly? how can better? better if make conventional getter , setter method instead , assigned values on other class? "hiding data" means?

thank you.

yes , no. point of encapsulation prevents other classes needing know class doing behind scenes. if store name in string (as you've done here), read/write file, or different, point of encapsulation user of class doesn't matter because they see string getname( ) , void setname (string name).

since modification of data entirely under control of class here, doesn't break encapsulation. if did store name file, potentially in getallinfo without other user of class being wiser. since observable behaviour outside of class still hides internals of class doing, it's still encapsulated.

that said, unconventional approach. describe in first paragraph, use of accessor methods (getters , setters) more idiomatic approach, , easier understand else using code. can do, doesn't break encapsulation, it's not i'd call elegant or typical.


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -