Genellikle protected
yalnızca erişilebilir t demektir o aynı paketteki alt sınıflar veya sınıflar.
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.
Örnek olarak, bu
public class Example extends Exception {
void method() {
Exception e = new Exception("Hello", null, false, false);
}
}
derleme değil ama bu
public class Example extends Exception {
Example() {
super("Hello", null, false, false);
}
}
yapar ve bu nedenle bu
yapar: Ancak burada JLS gelen yapıcıları için kurallar
public class Example {
void method() {
Exception e = new Exception("Hello", null, false, false) {};
}
}
Yani kural Bunlar açık, ama onların arkasındaki sebepleri anladığımı söyleyemem!
Derleme hatasını bilmek sorunun tanımlanmasında oldukça yararlı olabilir ... –
Bir http://stackoverflow.com/questions/5150748/protected-constructor-and-accessibility adresinden bir üst sınıfın korumalı kurucusunu kullanabilirsiniz. Bir alt sınıfın yapıcısında ancak bir üst sınıf örneğini başka bir yerde örneklememek için. – redge
Aşağıdakini aynı ya da daha az neden yapamazsınız public class Örnek {korunan int i;}/* başka bir pakette: */public class Uzantıları denetle Örnek {void m1 (Örnek ex) {ex.i = 2;} } ' – immibis