Confused with the concept of Java encapsulation

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:

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.

+4
source share
7 answers

. , , . name String ( ), / - , , , , String getName( ) void setName (String name).

, . name , getAllInfo, - , - . - , , .

, . , (getters seters) - , . , , , , .

+5

, .

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
  }

}
+7

(, ) ( !). , , getter setter. , , AdressBookEntry , , telNo , .

, . getters seters , , .

+3

, . , 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: "));
+1

. , , ( , , ) , (.. , , , , getter setter).

, . , , , . .

+1

, . , . - . , , , , xyz@abc.com. , .

+1

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.

0
source

All Articles