访问种本身的私有变量,很不理解的地方
访问类本身的私有变量,很不理解的地方
网上看到这个文章,表示没理解.http://my.oschina.net/magicly007/blog/164191
看代码吧:
第一个方法与你要访问的参数的field都在同一个TestPrivate类中,所以是可以的,但是第二个不再是同一个类,当然不能使用instance.privatedfield访问了。
第一个方法与你要访问的参数的field都在同一个TestPrivate类中,所以是可以的,但是第二个不再是同一个类,当然不能使用instance.privatedfield访问了。
为什么是同一个类就可以访问私有变量。参数其实是对象吧,对象怎么能访问私有变量?
网上看到这个文章,表示没理解.http://my.oschina.net/magicly007/blog/164191
看代码吧:
class TestPrivate2 { private int n; } public class TestPrivate { private int n; public void accessOtherPrivate(TestPrivate other) { other.n = 10;//这里是可以访问同类型的其他对象other的private字段的 System.out.println(other.n); } public void accessOtherPrivate(TestPrivate2 other) { // other.n = 10;//编译错误 // System.out.println(other.n);//编译错误 } public static void main(String[] args) { new TestPrivate().accessOtherPrivate(new TestPrivate()); } }
1 楼
arthur8
2013-10-01
2 楼
huangyunbin
2013-10-03
arthur8 写道
为什么是同一个类就可以访问私有变量。参数其实是对象吧,对象怎么能访问私有变量?