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?
Problem
Few important facts (which many people forget or are not aware of):
protected class Nested{...}its default constructor is alsoprotected.protectedvisibility can be accessed only from class whichYour
Class2 extends Class1so it only have access to members ofClass1(including access toNestedtype). But since itNested(even implicitly, it only inherits access to it since it isprotected)Nestedit can’t access
protectedelements fromNestedclass (including constructors).Solution:
To solve that problem make
Nestedconstructorpublicby eitherexplicitly creating no-argument constructor of
Nestedclass withpublicmodifier:making
Nestedclasspublic(its default constructor will also become public – see point 1.)