Confused with Java Encapsulation Concept

后端 未结 6 1757
抹茶落季
抹茶落季 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条回答
  •  北荒
    北荒 (楼主)
    2021-01-03 07:09

    You use setters and getters to make the variables accessible from outside your class. In your example you will have

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

    You will access the name property from a UI class (it isn't good to mix UI and business logic in the same class):

    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
      }
    
    }
    

提交回复
热议问题