Good afternoon!
I am reading a Java book on encapsulation, and it mentions the getter and setter method.
I read that in order to hide the attributes, I have to mark my instance variables as "PRIVATE" and make a "PUBLIC method getter and setterto access the data. Therefore, I tried to make similar, but not ordinary code, as described below:
getter and setter
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 my code above provide my variables because I assigned it directly? How can I do it better? Would it be better if I made a regular getter and settermethod and assigned values to another class? What does "data hiding" mean?
Thank.
. , , . name String ( ), / - , , , , String getName( ) void setName (String name).
name
String
String getName( )
void setName (String name)
, . name , getAllInfo, - , - . - , , .
getAllInfo
, . , (getters seters) - , . , , , , .
, .
public class AddressBookEntry { private String name; public void setName(String name) { this.name = name; } public String getName() { return name; } }
( - ):
public class MyPane extends JFrame { public getAllData() { String name = JOptionPane.showInputDialog("Enter Name: "); AddressBookEntry entry = new AddressBookEntry(); entry.setName(name); // You can't use entry.name = name } }
(, ) ( !). , , getter setter. , , AdressBookEntry , , telNo , .
AdressBookEntry
, . getters seters , , .
, . , Model-View-Controller (MVC), .
getter setter :
public String getName() { return name; } public void setName(String name) { this.name = name; }
, , , .
MVC , , -
myAddressBookEntry.setName(JOptionPane.showInputDialog("Enter Name: "));
. , , ( , , ) , (.. , , , , getter setter).
, . , , , . .
, . , . - . , , , , xyz@abc.com. , .
The terms encapsulation and information hiding are used interchangeably. By exposing the functionality of an object only through methods, you can prohibit assigning personal variables to any values that do not meet your requirements. One of the best ways to create a well-encapsulated class is to define its instance variables as private variables and allow access to these variables using public Methods.