I have a parent class containing a struct-like static nested class. The nested class must be public, as it should be returned to other classes where its contents are acted upon. However, only the parent class and its subclasses should be able to instantiate the nested class, as they know how to define its contents. All classes shown below are in different packages.
public abstract class Parent
{
public static class Data
{
public final String data1
...
public Data(String d1, ...)
{
data1 = d1;
...
}
}
public abstract Data getData();
}
public final class Subclass extends Parent
{
@Override
public Data getData()
{
return new Data(.....);
}
}
public class SomeOtherClass
{
public void someMethod()
{
final Data d = new Subclass().getData();
System.out.println(d.data1);
}
}
Declaring the Data
class protected
would stop getData()
from working properly. Decreasing the access modifier on the constructor of Data
would prevent subclasses of Parent
from working properly. What I want is something like protected-by-parent
, which I am guessing does not exist in Java.
Is there a suitable workaround? One possibility I can see is creating a protected
method in Parent
that effectively mirrors, calls, and returns from the constructor of Data
(which would be made private
). This however seems a bit messy; does anybody know of a better way/design?