Protected nested class not accessible to derived classes in other package
java
Solution
Problem
Few important facts (which many people forget or are not aware of):
- 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`.
- element with `protected` visibility can be accessed only from 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).
Solution:
To solve that problem make `Nested` constructor `public` by either
explicitly creating no-argument constructor of `Nested` class with `public` modifier:
package net;
public class Class1 {
protected static class Nested {
public Nested(){
//^^^^^^
}
}
}
making `Nested` class `public` (its default constructor will also become public - see point 1.)
package net;
public class Class1 {
public static class Nested {
//^^^^^^
}
}
Problem
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?