The code compiles fine but i dont understand how you can invoke printFromOuter2() if the reference type is Outerclass. How can i invoke printFromOuter2() in the above example? I dont know what to cast it to - to get to printFromOuter2()
O. Ziggy wrote:
The code compiles fine but i dont understand how you can invoke printFromOuter2() if the reference type is Outerclass. How can i invoke printFromOuter2() in the above example? I dont know what to cast it to - to get to printFromOuter2()
If the outer class (or any interface supported by the anonymous inner class) doesn't have the method, then you can't cast it to anything that can access the method. This is because the anonymous inner class definition is no longer in scope. Your only option in your example is to use reflection.
Yes the OuterClass class doesnt have the method. Here is an example of how i created the class which compiles fine.
What did you mean by this "This is because the anonymous inner class definition is no longer in scope."? Do you mean because the anonymous child class will only be alive for as long as there is a reference for it?
Thanks - The question i am still not sure of is why it is compilable if you cant access it. Henry suggests "Reflection" but i am not sure even with Reflection how you will access it if you dont know the name of the class.
Seconding Henry's comment "anonymous inner class definition is no longer in scope"... Since Anonymous Inner Class does not have name and trying out call like "oci2.printFromOuter2()" leads to compilation error indicating this method is not in "OuterClass"..