Confused with Java Encapsulation Concept

后端 未结 6 1716
抹茶落季
抹茶落季 2021-01-03 06:37

Good day!

I am reading a Java book about encapsulation and it mentioned the getter and setter method.

I\'ve read that to hide the attributes, I must mark my

6条回答
  •  Happy的楠姐
    2021-01-03 07:30

    This doesn't violate encapsulation, as it doesn't expose the internal data to another class. You may wish to look at Model-View-Controller (MVC) though to help separate out your interface from your data.

    Traditional you create a single getter and setter for each variable as needed like so:

    public String getName() {
      return name;
    }
    
    public void setName(String name) {
      this.name = name;
    }
    

    Don't create getters for variables that won't need to be accessed outside of the class, and don't create setters for variables that won't need to be set outside of the class.

    If following MVC and using the traditional getters and setters like above, you would have the view code elsewhere and call something like

    myAddressBookEntry.setName(JOptionPane.showInputDialog("Enter Name: "));
    

提交回复
热议问题