我们知道在Java中有3个访问修饰符,分别为public、protected、private。4个访问控制级别,分别为public、protected、默认和private。
其中类只能有public和默认访问级别。那么类的构造函数呢?下面就对类的构造函数的访问修饰符进行解说。
第一种情况:public访问控制级别
public访问控制级别的构造函数对于所有包中的类都是可见的。也就是说任何地方都可以实例化具有public修饰的构造函数的类。
第二种情况:protected访问控制级别
protected访问控制级别的构造函数对于同一个包中的类是可见的,也就是说其他包中类是不能够实例化具有protected修饰的构造函数的类。
例子:
package test;
public class C {
protected C(int arg1,int arg2){
System.out.println("C的protected构造函数");
}
}
package other;
import test.C;
public class Control {
public static void main(String[] args) {
C d = new C(1,3);
}
}
运行结果:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The constructor C(int, int) is not visible
at other.Control.main(Control.java:8)
第三种情况:默认访问控制级别
默认访问控制级别的构造函数同protected访问控制级别的构造函数一样,其他包的类无法实例化具有默认访问控制级别的构造函数的类。
package test;
public class C {
C(int arg1,int arg2){
System.out.println("C的protected构造函数");
}
}
package other;
import test.C;
public class Control {
public static void main(String[] args) {
C d = new C(1,3);
}
}
运行结果:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The constructor C(int, int) is not visible
at other.Control.main(Control.java:8)
第四种情况:private访问控制的构造函数
任何类都无法实例化具有private访问控制的构造函数的类。实际上就是没有什么意义。
package test;
public class C {
private C(int arg1,int arg2){
System.out.println("C的protected构造函数");
}
}
package test;
public class Control {
public static void main(String[] args) {
C d = new C(1,3);
}
}
运行结果:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The constructor C(int, int) is not visible
at test.Control.main(Control.java:6)