posted 23 years ago
There are some complex rules for Inner Classes which I dont fully understand. If I have an OuterA class which has and InnerA class, then I can create instances of InnerA in a different class OuterB without much problem.
However if OuterB is in a different Package(sub), and you create and instance of OuterA in OuterB and then you try to create an InnerA as
OuterA outerA = new OuterA();
OuterA.InnerA innerA = outerA.new InnerA();
then the compiler gives a strange error :
"OuterB.java:6: No constructor matching OuterA.InnerA(sub.OuterA) found in inner
class sub.OuterA. InnerA.
OuterA.InnerA innerA = outerA.new InnerA();"
When I am not passing any OuterA in the constructor of InnerA then why is it searching for one and giving this error?
So I construct a constructor for InnerA which takes an OuterA as an argument. I also call super() on this instance of OuterA that I am passing.
package sub;
public class OuterA
{
public class InnerA
{ public InnerA(OuterA oa){
oa.super();
}
}
}
Now when I try to create the InnerA inside OuterB, I have to pass the SAME instance of OuterA which I am using to create the InnerA.(why can't compiler automatically use the instance of OuterA for which it is creating InnerA).
OuterA.InnerA innerA = outerA.new InnerA(outerA);
Now every thing seems to work fine. What is going on here??