How do getters and setters work?

后端 未结 6 1968
北恋
北恋 2020-11-21 07:43

I\'m from the php world. Could you explain what getters and setters are and could give you some examples?

6条回答
  •  余生分开走
    2020-11-21 07:53

    In Java getters and setters are completely ordinary functions. The only thing that makes them getters or setters is convention. A getter for foo is called getFoo and the setter is called setFoo. In the case of a boolean, the getter is called isFoo. They also must have a specific declaration as shown in this example of a getter and setter for 'name':

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

    The reason for using getters and setters instead of making your members public is that it makes it possible to change the implementation without changing the interface. Also, many tools and toolkits that use reflection to examine objects only accept objects that have getters and setters. JavaBeans for example must have getters and setters as well as some other requirements.

提交回复
热议问题