java中的getter()和setter()

来源:互联网 发布:智能家居控制系统c语言 编辑:程序博客网 时间:2024/05/17 03:36

get set 方法主要是控制访问权限的, 一般类里面的属性设置为private,类外部无法直接访问 1.当需要读取的时候通过get方法获取 2.当需要修改的时候通过set方法设置 程序更加安全。 比如说


class Cat{         private String color;         public Cat(String color){             this.color = color;         }            public String getColor(){                 return this.color;          }   } 
这个例子中 是一个小猫类,他的颜色是与生俱来的,一般情况下后天无法改变。所以在构造方法中设置他的颜色,一只Cat对象被创建后,只能get到他的颜色,而不能set。


0 0
原创粉丝点击