Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to a protected constructor in Java

If I have a class A and its subclass B.

package washington;
public class A{
       protected A(){}
}

package washington;
public class B extends A{
      public B(){super();} // it works
      public static void main (String[] args){
      A b = new A(); // it does work.
       }
}

The class A has a protected constructor, but I cannot access the constructor in B. I think it is a rule, however, I cannot find a webpage describing this situation.. All that I saw mention protected can be accessed from subclass, same-package.... e.t.c.

package california;
public class A extends washington.A{
    public static void main (String[] args){
       new washington.A(); // it does not work.
    }
}

I wonder if this is because I use IntelliJ IDEA 2017.3.4.. compiler is javac 9.0.4

like image 230
kensuke1984 Avatar asked Oct 29 '25 11:10

kensuke1984


1 Answers

It seems that the problem is that you have your classes in different packages. Java doc says:

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.

like image 82
Kirill Simonov Avatar answered Oct 31 '25 01:10

Kirill Simonov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!