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?
The protected access modifier is accessible within the package. However, it can also accessible outside the package but through inheritance only. We can't assign protected to outer class and interface. If you make any constructor protected, you cannot create the instance of that class from outside the package.
In order to access your demo12 inner class from demo2 class, demo2 class has to extend demo1 . More over, inner classes are connected with instances of the class, so you can not call it directly from the static method. Check the difference between inner and nested classes. Show activity on this post.
As a member of the OuterClass , a nested class can be declared private , public , protected , or package private.
A nested class can be declared with any access modifier, namely private, public, protected, internal, protected internal, or private protected.
Few important facts (which many people forget or are not aware of):
protected class Nested{...}
its default constructor is also protected
.protected
visibility can be accessed only from class which
Your Class2 extends Class1
so it only have access to members of Class1
(including access to Nested
type). But since it
Nested
(even implicitly, it only inherits access to it since it is protected
)Nested
it can't access protected
elements from Nested
class (including constructors).
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 {
//^^^^^^
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With