Zazwyczaj protected
oznacza dostępne tylko t o podklas lub klasy w tym samym pakiecie. Jednak tutaj są zasady dla konstruktorów z JLS:
6.6.2.2. Qualified Access to a protected Constructor
Let C be the class in which a protected constructor is declared and let S be the innermost class in whose declaration the use of the protected constructor occurs. Then:
If the access is by a superclass constructor invocation super(...), or a qualified superclass constructor invocation E.super(...), where E is a Primary expression, then the access is permitted.
If the access is by an anonymous class instance creation expression new C(...){...}, or a qualified anonymous class instance creation expression E.new C(...){...}, where E is a Primary expression, then the access is permitted.
If the access is by a simple class instance creation expression new C(...), or a qualified class instance creation expression E.new C(...), where E is a Primary expression, or a method reference expression C :: new, where C is a ClassType, then the access is not permitted. A protected constructor can be accessed by a class instance creation expression (that does not declare an anonymous class) or a method reference expression only from within the package in which it is defined.
Jako przykład, to nie skompilować
public class Example extends Exception {
void method() {
Exception e = new Exception("Hello", null, false, false);
}
}
ale to robi
public class Example extends Exception {
Example() {
super("Hello", null, false, false);
}
}
i tak robi to
public class Example {
void method() {
Exception e = new Exception("Hello", null, false, false) {};
}
}
Rządzenie es są jasne, ale nie mogę powiedzieć, że rozumiem powody stojące za nimi!
Znajomość błędu kompilacji może być bardzo przydatna w diagnozowaniu problemu ... –
Spójrz na ten http://stackoverflow.com/questions/5150748/protected-constructor-and-accessibility możesz użyć chronionego konstruktora superklasy w konstruktorze podklasy, ale nie w celu utworzenia instancji nadklasy w dowolnym miejscu. – redge
Mniej więcej z tego samego powodu, dla którego nie można wykonać 'public class Example {protected int i;}/* w innym pakiecie: */public class Check extends Przykład {void m1 (Example ex) {ex.i = 2;} } ' – immibis