1. when used to instance variables and mehods
For example we have the java code below:
//code1
package test;
public class TestA {
private int i = 0;
int def = 0;
protected int pr = 0;
public int pub = 3;
}
//code 2
package test2;
import test.TestA;
public class TestB {
public static void main(String [] args){
TestA a = new TestA();
System.out.println(a.pub);//can only reference public variable
}
}
//code3
package test2;
import test.TestA;
public class TestB extends TestA {
public static void main(String [] args){
TestB b = new TestB();
System.out.println(b.pr);//can reference protected and public
}
}
So, we can get the conclusion here: Some times we like use default, but this can bring problems, default can only offer the reference in the same package, in code2, TestB is in another package, we new an TestA but we can't get access to it's default variable
def.
If we want to get access of variables in another package( except public), we have to use extention and the protected field. So don't use default when writing code, if we want't this field be accessed in another package we have to name this variable as protected or public.
2. used for class(only public and default can be used)
public means this class can be accessed anywhere
default: means this class can only be accessed by other classes in the same package.
3. used for constructor methods
Sometimes when we are writing constructor, we often use public, or sometimes we use default. But if we use default key word, we may meet trouble when a class B extends from a class A in another package and A use default key word for constructor. when we initialize B, we may meet trouble.
package test;
public class TestA {
private int value = 0;
//use the default keyword
TestA(){
System.out.println("superclass()");
}
//also use default keyword
TestA(int i){
i = this.value;
System.out.println("superclass("+i+")");
}
}package test2;
import test.TestA;
public class TestB extends TestA{
//trouble here, cause we can't get access to super class's constructor
public TestB() {
System.out.println("testB()");
}
public static void main(String [] args){
TestB b = new TestB();
}
}
本文探讨了Java中访问修饰符的使用方法,包括实例变量和方法、类及构造方法的访问控制。介绍了public、protected、默认(包访问)等修饰符的区别,并通过具体代码示例说明了它们的作用范围。
1875

被折叠的 条评论
为什么被折叠?



