Java Package level access

风流意气都作罢 提交于 2019-12-19 21:47:48

问题


I know that class members with default access control can be accessible at package level but i'm confused about what does package level access actually mean. If default members can be accessed at package level then shouldn't i be visible in class Test2 in following example? class 1-

package pkg1;
public class Test {
   int i=0;
}

class 2-

import pkg1.Test;
public class Test2 {

void get(){
    Test t = new Test();
    t.i=0;
}
}

Please help me getting this concept. Thanks in advance.


回答1:


Package level access means that only classes that are defined in the same package can access the package level variable. If you have to import Test, then I'm assuming that Test is in a different package and therefore it can't access i.

For Test2 to access i, define it in the same package as Test1.




回答2:


You forget to write

package pkg1; 

for Test2 class.

It should work now



来源:https://stackoverflow.com/questions/15347998/java-package-level-access

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!