class A{ private int i = 0; public int setI(i){ i ++; return i; } }
将变量声明为private,通过get set方法访问,这样你可以在get set方法中对变量进行控制。public class Example{ private int count; public int getCount(){ return this.count; } public void setCount(int count){ if (count != 0 ){ this.count = count; } } }
属性设置成私有类型 通过set设置属性的值 get获得属性的值 不直接访问属性
set/get 只能保证对象的封装,并不能保证安全性
那如果直接把 int count 设成pubilc的话 有什么区别么?;public int count;
如果是public,别的类可以直接赋值,这样就可能得到预期外的结果。 比如不希望count为0,若count是public,你无法干预对count的赋值。 而如果count是private,你可以在set中处理将count赋为0的情况。 Example example = new Example(); example.count = 0 ;
i ++;
return i;
}
}
private int count; public int getCount(){
return this.count;
} public void setCount(int count){
if (count != 0 ){
this.count = count;
}
}
}
比如不希望count为0,若count是public,你无法干预对count的赋值。
而如果count是private,你可以在set中处理将count赋为0的情况。 Example example = new Example();
example.count = 0 ;