Sololearn: Learn to Code
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1
If you are attempting to use, or needing to use, a class that is nested within a class, from a class other than the one it is nested in, then that class should not be nested within that class, but rather be an independent class of its own. However, the inner class if static can be accessed by using dot notation. If not static then an object of the inner class could be made within the outer class and then that object can be passed using a getter. See code below: class OuterClass { private InnerClass ic = new InnerClass(); public InnerClass getInnerClass() { return ic; } OuterClass() { System.out.println("Outer"); } static class StaticInnerClass { StaticInnerClass() { System.out.println("StaticInnerClass"); } } class InnerClass { InnerClass() { System.out.println("InnerClass"); } public void print() { System.out.println("InnerClass print method"); } } } public class Program { public static void main(String[] args) { OuterClass.StaticInnerClass sic = new OuterClass.StaticInnerClass(); OuterClass oc = new OuterClass(); OuterClass.InnerClass ic = oc.getInnerClass(); ic.print(); } }
21st Aug 2017, 2:16 AM
ChaoticDawg
ChaoticDawg - avatar