Search code examples
javainner-classesextend

how to define an inner class outside of the outer class


I have a question similar to "Defining inner class outside java file". But the questioner, there, just wanted to do something which is possible by letting the classes to be all in a package.

Similar to him I would like to define some classes as the inner objects of an outer object; but I would like to have access to the dynamic fields of that object. To avoid having a crowded classes, I would like to define them in some other "innerClasses.java". Using "extend" only makes me able to use its static fields. But, I would like to access the dynamic fields like an inner object.

As a short example (but in fact a big example would be problematical) I would like this class in the class "OuterClass.java"

public class OuterClass{
    double nonStaticField
}

And each of these classes in other classes

public class InnerClass1OfOuterClass{
    ...
}

public class InnerClass2OfOuterClass{
    ...
}

public class InnerClass3OfOuterClass{
    ...
}

public class InnerClass4OfOuterClass{
    ...
}

....

Solution

  • The "natural" way would be the other way around: to let an inner class extend some abstract class containing the major code:

    class Outer {
        class Inner extends InnerBase<Outer> {
            ... little code
        }
    }
    
    class InnerBase<T> {
        protected int eger;
        ... most code
    }
    

    Then there is delegating to a different class too.

    Now if you still want to extend Inner:

    class InnerBase<T> {
        protected int eger;
        ... most code
    }
    
    class Sinner extends Outer.Inner {
    }
    
    Outer outer = new Outer();
    Inner sinner = outer.new Sinner();
    

    For practical purposes you might create in Outer

    protected Inner createInner() { return new Inner(); }
    

    and extend Outer, overriding the factory method createInner.

    This code design might be a bit circumstantial, hence my "natural" in the beginning.