I'd like to create a subclass accessible only from an instance of the superclass, but not from the superclass itself, to be sure that the superclass' variables have been initialized. For example:
public class SuperClass
{
int num;
SuperClass(int number){
num = number;
}
//Make this\/ accessible from instance only
class SubClass
{
SubClass(){}
public int read(){
return num;
}
}
}
In another file:
public void err(){
SuperClass.SubClass obj = new SuperClass.SubClass(); //Error! Superclass is not an instance
System.out.println(obj.read());
}
public void right(){
SuperClass sup = new SuperClass(3);
SuperClass.SubClass obj = new sup.SubClass(); //Correct, sup is an instance
System.out.println(obj.read()) //Print 3
That's not possible. Non-static inner classes have to be instantiated through an instance of an outer class. See this link for more info.