Encapsulation and Getters

后端 未结 4 1879
青春惊慌失措
青春惊慌失措 2020-12-19 23:56

I was reading this article on why getter and setters are evil. The article doesn\'t say not to use them ever, but, it\'s telling y

4条回答
  •  猫巷女王i
    2020-12-20 00:41

    Think of it this way: Getters (public functions) are a bridge for private attributes.

    I'll write you a simple example to modify your TextField using OOP.

    Book class:

    public final class Book {
    private String title;
    //Authors is class with the attributes authorFirstname, authorLastname
    private List listofAuthors;
    
    
    public Book(String title, List listofAuthors)
    {
        //initialization
    }
    public String getTitle() {
    return this.title; }
    }
    

    GUI:

    author1 = new Author("jhon");
    author 2 = new Author("alsojhon");
    list = new ArrayList();
    list.add(author1);
    list.add(author2)
    b = new Book("stack",list);
    JTextField field;
    field.setText(b.getTitle());
    

提交回复
热议问题