Reputation: 1364
I'm puzzled by the possibility to call new on an instance, like
InnerClass sc = pc.new InnerClass();
I understand how to use it, but my question is about fully understanding this. Like:
Where is it described in the JAVA documentation?
Is this a recommended solution that should be used, or is there a better way?
Why doesn't a plain "new" work?
I saw it in a code example, and I have worked out enough to understand that I'm unable to use a plain "new" in a static context.
This is the full context as a runnable example:
class ParentClass{
ParentClass(){
}
public static void main(String[] args){
ParentClass pc = new ParentClass();
InnerClass sc = pc.new InnerClass();
}
class InnerClass {
InnerClass() {
System.out.println("I'm OK");
}
}
}
Upvotes: 2
Views: 54
Reputation: 20033
Disclaimer: The terms "parent class" and "sub class" you use are not correct in your example, so my example below will use the correct terms "outer class" and "inner class" (thanks to @eis for the hint).
Where is it described in the JAVA documentation?
See @eis' comment to my answer for a link.
Is this a recommended solution that should be used, or is there a better way?
It depends – on what you need it for.
If SubClass
doesn't need any information of an instance of ParentClass
, it could (and should) be either made static or extracted to not be an inner class at all anymore. In that case, you can just call new
on it without having an instance of ParentClass
.
Why doesn't a plain "new" work?
Because SubClass
may refer to information of the surrounding instance, which requires you to specify that instance. It's not a sub class in the sense that it extends ParentClass
, but instead its type becomes a member of the outer class.
Consider this (and see it in action here):
public class OuterClass {
private int field;
public OuterClass(int field) {
this.field = field;
}
class InnerClass {
public int getOuterClassField() {
// we can access the field from the surrounding type's instance!
return OuterClass.this.field;
}
}
public static void main(String[] args) throws Exception {
OuterClass parent = new OuterClass(42);
// prints '42'
System.out.println(parent.new InnerClass().getOuterClassField());
// cannot work as it makes no sense
// System.out.println(new InnerClass().getOuterClassField());
}
}
If you were able to simply do new InnerClass()
, there's no way of knowing what getOuterClassField
should return since it is connected to the instance of its surrounding type (rather than just the type itself).
Upvotes: 3