类如下:
public Test{
//private variable
private int test_variable = -1; //construction
public Test(){
}
public static void main(String[] args){
//new an object
Test test = new Test();
//try to access the private variable ( test_variable )
System.out.println(test.test_variable);
}
}===============================================================
source code end
===============================================================
javac Test.java ---- pass
===============================================================
java Test ---- -1
===============================================================
为什么在像main这样的static方法中就可以直接访问它所属类的private数据成员?
请高手指点!
public Test{
//private variable
private int test_variable = -1; //construction
public Test(){
}
public static void main(String[] args){
//new an object
Test test = new Test();
//try to access the private variable ( test_variable )
System.out.println(test.test_variable);
}
}===============================================================
source code end
===============================================================
javac Test.java ---- pass
===============================================================
java Test ---- -1
===============================================================
为什么在像main这样的static方法中就可以直接访问它所属类的private数据成员?
请高手指点!
{ public static void main(String[] args)
{
Test t=new Test();
System.out.println(t.test_variable);//这句报错了,说test_variable不可视
}
}按理来讲,如果test_variable是用public来修饰的,才可以t.test_variable这样用,现在原因只有一个,因为main()是在class Test里面的,这样才可以。
只向外界提供方法(接口)来访问属性,达到隐藏实现的目的
通俗一点讲就是不让别人直接访问属性
象private ,protected,public 这些访问控制修饰符 就可以达到这样的目的
说的很好,就这么个意思的,
oop思想你的明白?