Reputation: 7
Considering the following code:
public abstract class AbstractA
{
public static final class B
{
protected B(){}
}
}
// a class (in another package) that inherits from AbstractA
public class C extends AbstractA
{
B[] arrayOfB=new B[10];
for(byte i=0; i<=arrayOfB.length; i++)
{
arrayOfB[i]=new B();
}
}
In class C I can define arrayOfB because class B is static & public but I cant instanciate an object of this. Eclipse says: The constructor A.B() is not visible
If class C was in the same package as the class A, I could instantiate it. How can I keep the constructor B() protected and still create an object of this knowing that the class C inherits from A?
Upvotes: 0
Views: 137
Reputation: 28951
It is nothing to do with inner classes. Your B
constructor is protected it means only subclasses could access it, but you define the class as final
, it doesn't make sense. Maybe you could add a factory method to the AbstractA which creates B
instances, outer class has access to its inner classes, even for private methods.
public abstract class AbstractA
{
protected B newB() {return new B();}
public static final class B
{
private B(){}
}
}
// a class (in another package) that inherits from AbstractA
public class C extends AbstractA
{
B[] arrayOfB=new B[10];
for(byte i=0; i<=arrayOfB.length; i++)
{
arrayOfB[i]=this.newB();
}
}
Upvotes: 3
Reputation: 7804
The protected
specifier allows access by all subclasses of the class in question, whatever package they reside in, as well as to other code in the same package.
In your case, the class C
resides in different package and hence you are not allowed to instantiate A.B()
due to above reason.
Please remember, protected
specifier permits only inheritance in different package. You cannot access them directly..
As a solution to your problem, move the class C
in the same package as that of AbstractA
to make B
accessible.
Upvotes: 0
Reputation: 1190
If you want to extends a class outside its package it must have a constructor that is public or protected because in Java every constructor must call a constructor from its superclass.
(The implicit super()
call will fail.)
Upvotes: 0
Reputation: 8874
Public static classes that are nested are the same as public classes in a separate file. So you cannot see B's constructor, because you are not B's descendant, nor are you in the same package.
Upvotes: 2