对于java的修饰符,无外乎讲的都是调用的范围讲解,其实每一个简单的背后都还是有很多的细节可以深究学习的。
public,protected,default,private,这四种级别的修饰符都可以用来修饰类、方法和字段。
public
protected
default
private
记得学习的时候,老师说public属性的字段,在定义的时候要慎重,模棱两可,不甚了解。今天学习多线程开发的时候,
突然发现一个实例:
public class MutablePoint {
public int x, y;
public MutablePoint() {
x = 0;
y = 0;
}
public MutablePoint(MutablePoint p) {
this.x = p.x;
this.y = p.y;
}
}
说是线程不安全的,一时没有反应过来,自己一番琢磨终于理解透彻。如果把x,y定义为public类型,在多线程使用时,修改
其属性值,会得到意想不到的结果,导致程序错误。
public class MutablePointTest extends Thread{
String value;
MutablePoint mp;
public MutablePointTest(String val,MutablePoint mp){
this.value=val;
this.mp=mp;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MutablePoint mp = new MutablePoint();
for(int i=0;i<900;i++){
new MutablePointTest(String.valueOf(i),mp).start();
}
}
public void run(){
mp.x=Integer.valueOf(value);
mp.y=Integer.valueOf(value);
if(mp.x != mp.y && (mp.x !=Integer.valueOf(value)))
System.out.println("the thread name is "+ value +" ,x="+ mp.x+ " ,y="+ mp.y);
}
}
结果:
the thread name is 431 ,x=478 ,y=478
the thread name is 569 ,x=571 ,y=571
如果所起的线程数越多,则出错的数据越多。
在做demo的时候,起先把MutablePoint mp = new MutablePoint();定义在MutablePointTest属性里面,结果老是得不到预想结果,
可见自己对对象的理解还是不够透彻,只是停留在字的层面,凡事还是要多实践,多练习。