rubixibuc rubixibuc - 3 months ago 14
Java Question

Protected nested class not accessible to derived classes in other package

Here is what I'm trying to accomplish

File 1: ./net/Class1.java

package net;

public class Class1
{
protected static class Nested
{

}
}


File 2: ./com/Class2.java

package com;

import net.Class1;

public class Class2 extends Class1
{
Nested nested = new Nested();
}


Here is the error I'm getting

>javac ./net/Class1.java ./com/Class2.java
.\com\Class2.java:7: error: Nested() has protected access in Nested
Nested nested = new Nested();


Is this error expected? Am I doing something wrong?

Answer

Few important facts (which many people forget or are not aware of):

  1. default constructors (including ones for static and non-static nested classes) have same visibility as visibility of class which they belong to. So in case of protected class Nested{...} its default constructor is also protected.
  2. element with protected visibility can be accessed only by class which
    • belongs to same package as class which declared that element,
    • extends (explicitly or implicitly) class which declared it.

Your Class2 extends Class1 so it only have access to members of Class1 (including access to Nested type). But since it

  • doesn't extend Nested (even implicitly, it only inherits access to it since it is protected)
  • doesn't belong to same package as Nested

it can't access protected elements from Nested class (including constructors).

To solve that problem make Nested constructor public.

package net;

public class Class1 {

    protected static class Nested {

        public Nested(){
      //^^^^^^
        }

    }

}