Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protected inner-class is NOT accessible from subclass of another package

I have the following code in Java:

package a;
public classs ClassInOtherPackage{
    protected void protectedMethod(){}
     protected class protectedInnerClass {}
}

package b;
import a.*;
public class MyClass extends ClassInOtherPackage{
  public MyClass(){
    MyClass x = new MyClass();
    x.protectedMethod();  //<-- This one ok
    //UPDATED: Declaration is ok
    MyClass.protectedInnerClass y; //<-- This one ok
    //UPDATED: Only when instantiated is not allowed, why?
    y = x.new protectedInnerClass(); //<-- Not allow when instantiated.
  }
}

Refer to the Java documentation:

"The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package."

Why can't I instantiate the inner protected class as shown above?

like image 510
user2575537 Avatar asked Oct 25 '25 03:10

user2575537


1 Answers

In JLS 8.8.9

8.8.9. Default Constructor

... if the class is declared protected, then the default constructor is implicitly given the access modifier protected (§6.6); ...

So the implicitly declared constructor is:

protected class protectedInnerClass {
    protected protectedInnerClass(){
        super();
    }
}

You code won't compile because the constructer is inaccessible.

like image 188
johnchen902 Avatar answered Oct 26 '25 16:10

johnchen902



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!